text:
package com.ctrip.hermes.portal.resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unidal.dal.jdbc.DalException;
import org.unidal.dal.jdbc.DalNotFoundException;

import com.alibaba.fastjson.JSON;
import com.ctrip.hermes.core.bo.SchemaView;
import com.ctrip.hermes.core.utils.PlexusComponentLocator;
import com.ctrip.hermes.core.utils.StringUtils;
import com.ctrip.hermes.meta.entity.Codec;
import com.ctrip.hermes.meta.entity.Topic;
import com.ctrip.hermes.metaservice.model.Schema;
import com.ctrip.hermes.metaservice.service.SchemaService;
import com.ctrip.hermes.metaservice.service.TopicService;
import com.ctrip.hermes.portal.resource.assists.RestException;
import com.google.common.io.ByteStreams;

@Path("/schemas/")
@Singleton
@Produces(MediaType.APPLICATION_JSON)
public class SchemaResource {

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

	private SchemaService schemaService = PlexusComponentLocator.lookup(SchemaService.class);

	private TopicService topicService = PlexusComponentLocator.lookup(TopicService.class);

	/**
	 *
	 * @param fileInputStream
	 * @param fileHeader
	 * @param jarInputStream
	 * @param jarHeader
	 * @param content
	 * @param topicId
	 * @return
	 */
	@POST
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public Response createSchema(@FormDataParam("file") InputStream fileInputStream,
	      @FormDataParam("file") FormDataContentDisposition fileHeader, @FormDataParam("schema") String content,
	      @FormDataParam("topicId") long topicId) {
		logger.debug("create schema, topicId {}, content {}, fileHeader {}", topicId, content, fileHeader);
		if (StringUtils.isEmpty(content)) {
			throw new RestException("HTTP POST body is empty", Status.BAD_REQUEST);
		}
		SchemaView schemaView = null;
		try {
			schemaView = JSON.parseObject(content, SchemaView.class);
		} catch (Exception e) {
			logger.warn("parse schema failed, content {}", content);
			throw new RestException(e, Status.BAD_REQUEST);
		}

		Topic topic = topicService.findTopicById(topicId);
		if (topic == null) {
			throw new RestException("Topic not found: " + topicId, Status.NOT_FOUND);
		}
		if (Codec.AVRO.equals(topic.getCodecType()) && !fileHeader.getFileName().endsWith(".avsc")) {
			throw new RestException("Schema file name must end with .avsc", Status.BAD_REQUEST);
		}

		byte[] fileContent = null;
		if (fileInputStream != null) {
			try {
				fileContent = ByteStreams.toByteArray(fileInputStream);
			} catch (IOException e) {
				logger.warn("Read file input stream failed", e);
				throw new RestException(e, Status.BAD_REQUEST);
			}
		} else {
			if ("avro".equalsIgnoreCase(schemaView.getType())) {
				throw new RestException("avro schema file needed.", Status.BAD_REQUEST);
			}
		}

		try {
			int avroid = -1;
			// If the avro schema has been created, return CONFLICT
			if ("avro".equalsIgnoreCase(schemaView.getType())) {
				avroid = schemaService.checkAvroSchema(topic.getName() + "-value", fileContent);
				if (schemaService.isAvroSchemaExist(topic, avroid)) {
					schemaView = schemaService.getSchemaView(topic.getSchemaId());
					return Response.status(Status.CONFLICT).entity(schemaView).build();
				}
			}
			schemaView = schemaService.createSchema(schemaView, topic);
			schemaView = schemaService.updateSchemaFile(schemaView, fileContent, fileHeader);
		} catch (Exception e) {
			logger.warn("Create schema failed", e);
			if (schemaView.getId() != null) {
				try {
					schemaService.deleteSchema(schemaView.getId());
				} catch (DalException e1) {
					throw new RestException(e1, Status.INTERNAL_SERVER_ERROR);
				}
			}
			throw new RestException(e.getMessage(), Status.INTERNAL_SERVER_ERROR);
		}
		return Response.status(Status.CREATED).entity(schemaView).build();
	}

	/**
	 *
	 * @param schemaId
	 * @return
	 */
	@DELETE
	@Path("{id}")
	public Response deleteSchema(@PathParam("id") long schemaId) {
		logger.debug("delete schema {}", schemaId);
		try {
			schemaService.deleteSchema(schemaId);
		} catch (DalNotFoundException e) {
			throw new RestException("Schema not found: " + schemaId, Status.NOT_FOUND);
		} catch (DalException e) {
			logger.warn("Delete schema failed", e);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}
		return Response.status(Status.OK).build();
	}

	/**
	 *
	 * @param schemaId
	 * @return
	 */
	@GET
	@Path("{id}/schema")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response downloadSchema(@PathParam("id") long schemaId) {
		logger.debug("download schema {}", schemaId);
		Schema schema = null;
		try {
			schema = schemaService.getSchemaMeta(schemaId);
		} catch (DalNotFoundException e) {
			throw new RestException("Schema not found: " + schemaId, Status.NOT_FOUND);
		} catch (Exception e) {
			logger.warn("Download schema failed", e);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}

		String fileProperties = schema.getSchemaProperties();
		if (StringUtils.isEmpty(fileProperties)) {
			throw new RestException("Schema file not found: " + schemaId, Status.NOT_FOUND);
		}

		return Response.status(Status.OK).header("content-disposition", fileProperties).entity(schema.getSchemaContent())
		      .build();
	}

	/**
	 *
	 * @param schemaId
	 * @return
	 */
	@GET
	@Path("{id}/jar")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response downloadJar(@PathParam("id") long schemaId) {
		logger.debug("download jar {}", schemaId);
		Schema schema = null;
		try {
			schema = schemaService.getSchemaMeta(schemaId);
		} catch (DalNotFoundException e) {
			throw new RestException("Schema not found: " + schemaId, Status.NOT_FOUND);
		} catch (Exception e) {
			logger.warn("Download jar failed", e);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}

		String fileProperties = schema.getJarProperties();
		if (StringUtils.isEmpty(fileProperties)) {
			throw new RestException("Schema file not found: " + schemaId, Status.NOT_FOUND);
		}

		return Response.status(Status.OK).header("content-disposition", fileProperties).entity(schema.getJarContent())
		      .build();
	}

	@POST
	@Path("{id}/deploy")
	public Response deployMaven(@PathParam("id") long schemaId, @QueryParam("groupId") String groupId,
	      @QueryParam("artifactId") String artifactId, @QueryParam("version") String version,
	      @QueryParam("repositoryId") @DefaultValue("snapshots") String repositoryId) {
		logger.debug("deploy maven {} {} {} {} {}", schemaId, groupId, artifactId, version, repositoryId);
		Schema schema = null;
		try {
			schema = schemaService.getSchemaMeta(schemaId);
			schemaService.deployToMaven(schema, groupId, artifactId, version, repositoryId);
		} catch (DalNotFoundException e) {
			throw new RestException("Schema not found: " + schemaId, Status.NOT_FOUND);
		} catch (Exception e) {
			logger.warn("Deploy jar failed", e);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}

		return Response.status(Status.OK).build();
	}

	/**
	 *
	 * @param name
	 * @return
	 */
	@GET
	@Path("{id}")
	public SchemaView getSchema(@PathParam("id") long schemaId) {
		logger.debug("get schema {}", schemaId);
		SchemaView schema = null;
		try {
			schema = schemaService.getSchemaView(schemaId);
		} catch (DalNotFoundException e) {
			throw new RestException("Schema not found: " + schemaId, Status.NOT_FOUND);
		} catch (Exception e) {
			logger.warn("get schema failed", e);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}
		return schema;
	}

	/**
	 *
	 * @param schemaName
	 * @return
	 */
	@GET
	public List<SchemaView> findSchemas() {
		List<SchemaView> returnResult = new ArrayList<SchemaView>();
		try {
			List<Schema> schemaMetas = schemaService.listLatestSchemaMeta();
			for (Schema schema : schemaMetas) {
				SchemaView schemaView = SchemaService.toSchemaView(schema);
				returnResult.add(schemaView);
			}
		} catch (Exception e) {
			logger.warn("list latest schema failed", e);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}
		return returnResult;
	}

	@POST
	@Path("{id}/compatibility")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public Response compatibility(@PathParam("id") Long schemaId, @FormDataParam("file") InputStream fileInputStream,
	      @FormDataParam("file") FormDataContentDisposition fileHeader) {
		logger.debug("test compatilibity schemaId {} fileHeader {}", schemaId, fileHeader);
		Schema schema = null;
		try {
			schema = schemaService.getSchemaMeta(schemaId);
		} catch (DalNotFoundException e) {
			throw new RestException("Schema not found: " + schemaId, Status.NOT_FOUND);
		} catch (Exception e) {
			logger.warn("get schema failed, schemaId {}", schemaId);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}

		boolean result = false;
		try {
			byte[] fileContent = ByteStreams.toByteArray(fileInputStream);
			result = schemaService.verifyCompatible(schema, fileContent);
		} catch (Exception e) {
			logger.warn("Read input stream failed", e);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}
		Map<String, Object> entity = new HashMap<>();
		entity.put("is_compatible", result);
		return Response.status(Status.OK).entity(entity).build();
	}

	@GET
	@Path("{id}/compatibility")
	public Response getCompatibility(@PathParam("id") Long schemaId) {
		logger.debug("get compatibility {}", schemaId);
		Schema schema = null;
		try {
			schema = schemaService.getSchemaMeta(schemaId);
		} catch (DalNotFoundException e) {
			throw new RestException("Schema not found: " + schemaId, Status.NOT_FOUND);
		} catch (Exception e) {
			logger.warn("get schema failed, schemaId {}", schemaId);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}

		String result = null;
		try {
			result = schemaService.getCompatible(schema);
		} catch (Exception e) {
			logger.warn("get compatible failed", e);
			throw new RestException(e, Status.INTERNAL_SERVER_ERROR);
		}
		return Response.status(Status.OK).entity(result).build();
	}
}


text:
@interface ZOEMomentStepViewController ()
@property (nonatomic,strong) UILabel            *label;
@property (nonatomic,strong) UIButton           *button;
@end

@implementation ZOEMomentStepViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"计步";
    [self.view addSubview:self.label];
    [self.view addSubview:self.button];

    __weak typeof(self)weakSelf = self;
    [ZOEMomentStep getMomentStepWithSucessBlock:^(CMPedometerData *data) {
        __strong typeof(self)strongSelf = weakSelf;
        if (!strongSelf)return;
        dispatch_async(dispatch_get_main_queue(), ^{
            strongSelf.label.text = [NSString stringWithFormat:@"%@步",data.numberOfSteps];
        });
    } errorBlock:^(id error) {
        __strong typeof(self)strongSelf = weakSelf;
        if (!strongSelf)return;
        NSString *str = error;
        [strongSelf showHintError:str];
    }];
}

//UILabel
- (UILabel *)label {
    if (!_label) {
        _label = [[UILabel alloc]init];
        _label.font = [UIFont systemFontOfSize:15];
        _label.textAlignment = NSTextAlignmentCenter;
        _label.frame = CGRectMake(0,
                                  70,
                                  [UIScreen mainScreen].bounds.size.width,
                                  40);
        _label.text = @"0步";
    }
    return _label;
}

- (UIButton *)button {
    if (!_button) {
        _button = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button setTitle:@"停止计步" forState:UIControlStateNormal];
        [_button setBackgroundColor:[UIColor blueColor]];
        [_button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
        _button.frame = CGRectMake(0,
                                    200,
                                    [UIScreen mainScreen].bounds.size.width,
                                    40);
    }
    return _button;
}

- (void)clickButton {
    [ZOEMomentStep stopPedometerUpdates];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package com.jeesuite.common;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 *
 * <br>
 * Class Name   : ThreadLocalContext
 *
 * @author jiangwei
 * @version 1.0.0
 * @date 2020年6月30日
 */
public class ThreadLocalContext {

	private static ThreadLocal<Map<String, Object>> context = new ThreadLocal<>();

	public static void set(String key,Object value){
		if(value == null)return;
		getContextMap().put(key, value);
	}

	public static String getStringValue(String key){
		if(context.get() == null)return null;
		return Objects.toString(context.get().get(key), null);
	}

	public static boolean exists(String key){
		if(context.get() == null)return false;
		return context.get().containsKey(key);
	}

	@SuppressWarnings("unchecked")
	public static <T> T get(String key){
		if(context.get() == null)return null;
		return (T) context.get().get(key);
	}

	public static void remove(String...keys){
		if(context.get() == null)return;
		for (String key : keys) {
			context.get().remove(key);
		}
	}

	public static boolean isEmpty(){
		return context.get() == null || context.get().isEmpty();
	}

	public static void unset(){
		if(context.get() != null){
			context.get().clear();
			context.remove();
		}
	}

	private static Map<String, Object> getContextMap(){
		if(context.get() == null){
			context.set(new HashMap<>());
		}
		return context.get();
	}

}


text:
const {BrowserWindow} = require('electron');
class FacebookPopup extends BrowserWindow{
	constructor(name, url, session){
		super({
			title: name,
			minWidth: 550,
			minHeight: 280,
			width: 550,
			height: 280,
			show: true,
			icon: App.icon,
			session: session,
			webPreferences: {
			  preload: `${__dirname}/facebook/preload.js`,
			  nodeIntegration: false,
			  plugins: true
			}
		});
		this.loadURL(url);
		this.setMenu(null);
		if(app.settings.ShowDevTools) this.openDevTools();
	}
}
module.exports = FacebookPopup;


text:
@interface PodsDummy_Pods_Tests_OGRSAEncryption : NSObject
@end
@implementation PodsDummy_Pods_Tests_OGRSAEncryption
@end


text:
package org.apache.drill.exec.store.http;

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

import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.store.http.util.HttpProxyConfig;
import org.apache.drill.exec.store.http.util.HttpProxyConfig.ProxyType;
import org.apache.drill.test.BaseTest;
import org.apache.drill.test.ConfigBuilder;
import org.junit.Ignore;
import org.junit.Test;

import com.typesafe.config.Config;

public class TestHttpProxy extends BaseTest {

  @Test
  public void testBasics() {
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .type("socks")
        .host(" foo.com ")
        .port(1234)
        .username(" bob ")
        .password(" secret ")
        .build();
    assertEquals(ProxyType.SOCKS, proxy.type);
    assertEquals("foo.com", proxy.host);
    assertEquals(1234, proxy.port);
    assertEquals("bob", proxy.username);
    assertEquals("secret", proxy.password);
  }

  @Test
  public void testURL() {
    // See https://www.shellhacks.com/linux-proxy-server-settings-set-proxy-command-line/
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .url("http://bob:secret@foo.com:1234")
        .build();
    assertEquals(ProxyType.HTTP, proxy.type);
    assertEquals("foo.com", proxy.host);
    assertEquals(1234, proxy.port);
    assertEquals("bob", proxy.username);
    assertEquals("secret", proxy.password);
  }

  @Test
  public void testURLAndConfig() {
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .url("http://foo.com:1234")
        .username("bob")
        .password("secret")
        .build();
    assertEquals(ProxyType.HTTP, proxy.type);
    assertEquals("foo.com", proxy.host);
    assertEquals(1234, proxy.port);
    assertEquals("bob", proxy.username);
    assertEquals("secret", proxy.password);
  }

  @Test
  public void testNone() {
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .type("")
        .host("foo.com")
        .port(1234)
        .username("bob")
        .password("secret")
        .build();
    assertEquals(ProxyType.NONE, proxy.type);
    assertNull(proxy.host);
    assertNull(proxy.username);
    assertNull(proxy.password);
  }

  @Test
  public void testBlankType() {
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .type("  ")
        .host("foo.com")
        .port(1234)
        .username("bob")
        .password("secret")
        .build();
    assertEquals(ProxyType.NONE, proxy.type);
    assertNull(proxy.host);
    assertNull(proxy.username);
    assertNull(proxy.password);
  }

  @Test
  public void testBadType() {
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .type("bogus")
        .host("foo.com")
        .port(1234)
        .username("bob")
        .password("secret")
        .build();
    assertEquals(ProxyType.NONE, proxy.type);
    assertNull(proxy.host);
    assertNull(proxy.username);
    assertNull(proxy.password);
  }

  @Test
  public void testHttpConfig() {
    Config config = new ConfigBuilder()
        .put(ExecConstants.HTTP_PROXY_URL, "http://bob:secret@foo.com:1234")
        .build();
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .fromHttpConfig(config)
        .build();
    assertEquals(ProxyType.HTTP, proxy.type);
    assertEquals("foo.com", proxy.host);
    assertEquals(1234, proxy.port);
    assertEquals("bob", proxy.username);
    assertEquals("secret", proxy.password);
  }

  @Test
  public void testHttpUrlConfig() {
    Config config = new ConfigBuilder()
        .put(ExecConstants.HTTP_PROXY_URL, "")
        .put(ExecConstants.HTTP_PROXY_TYPE, "socks")
        .put(ExecConstants.HTTP_PROXY_HOST, "foo.com")
        .put(ExecConstants.HTTP_PROXY_PORT, 1234)
        .put(ExecConstants.HTTP_PROXY_USER_NAME, "bob")
        .put(ExecConstants.HTTP_PROXY_PASSWORD, "secret")
        .build();
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .fromHttpConfig(config)
        .build();
    assertEquals(ProxyType.SOCKS, proxy.type);
    assertEquals("foo.com", proxy.host);
    assertEquals(1234, proxy.port);
    assertEquals("bob", proxy.username);
    assertEquals("secret", proxy.password);
  }

  @Test
  public void testHttpsUrlConfig() {
    Config config = new ConfigBuilder()
        .put(ExecConstants.HTTPS_PROXY_URL, "https://bob:secret@foo.com:1234")
        .build();
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .fromHttpsConfig(config)
        .build();
    assertEquals(ProxyType.HTTP, proxy.type);
    assertEquals("foo.com", proxy.host);
    assertEquals(1234, proxy.port);
    assertEquals("bob", proxy.username);
    assertEquals("secret", proxy.password);
  }

  @Test
  public void testHttpsConfig() {
    Config config = new ConfigBuilder()
        .put(ExecConstants.HTTPS_PROXY_URL, "")
        .put(ExecConstants.HTTPS_PROXY_TYPE, "socks")
        .put(ExecConstants.HTTPS_PROXY_HOST, "foo.com")
        .put(ExecConstants.HTTPS_PROXY_PORT, 1234)
        .put(ExecConstants.HTTPS_PROXY_USER_NAME, "bob")
        .put(ExecConstants.HTTPS_PROXY_PASSWORD, "secret")
        .build();
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .fromHttpsConfig(config)
        .build();
    assertEquals(ProxyType.SOCKS, proxy.type);
    assertEquals("foo.com", proxy.host);
    assertEquals(1234, proxy.port);
    assertEquals("bob", proxy.username);
    assertEquals("secret", proxy.password);
  }

  @Test
  public void testConfigForUrl() {
    Config config = new ConfigBuilder()
        .put(ExecConstants.HTTP_PROXY_URL, "http://bob:secret@foo.com:1234")
        .put(ExecConstants.HTTPS_PROXY_URL, "http://alice:s3cr3t@bar.com:2345")
        .build();
    doTestConfigForUrl(config);
  }

  private void doTestConfigForUrl(Config config) {
    HttpProxyConfig proxy = HttpProxyConfig.builder()
        .fromConfigForURL(config, "http://google.com")
        .build();
    assertEquals(ProxyType.HTTP, proxy.type);
    assertEquals("foo.com", proxy.host);
    assertEquals(1234, proxy.port);
    assertEquals("bob", proxy.username);
    assertEquals("secret", proxy.password);

    proxy = HttpProxyConfig.builder()
        .fromConfigForURL(config, "https://google.com")
        .build();
    assertEquals(ProxyType.HTTP, proxy.type);
    assertEquals("bar.com", proxy.host);
    assertEquals(2345, proxy.port);
    assertEquals("alice", proxy.username);
    assertEquals("s3cr3t", proxy.password);
  }

  // To run this test, set two env vars in your run/debug
  // configuration, then comment out the @Ignore:
  // http_proxy=http://bob:secret@foo.com:1234
  // https_proxy=http://alice:s3cr3t@bar.com:2345
  @Test
  @Ignore("Requires manual setup")
  public void testEnvVar() {
    Config config = new ConfigBuilder()
        .build();
    doTestConfigForUrl(config);
  }
}


text:
                <button type="button" class="close" data-dismiss="modal">×Close</button>

Project settings

            {!! Form::model($sprint->project, ['route' => ['project_settings_path', $sprint->project->slug], 'method' => 'PUT']) !!}

                    Edit your project settings here. Please note that if you choose to work with Phabricator's workboards and check "Use workboards instead of statuses" you should have at least one column symbolizing a "closed" state for tasks and copy its name to the field below.

                            {!! Form::checkbox('workboard_mode') !!}
                            Use workboards instead of statuses

                        {!! Form::label('closed_statuses', 'Closed status columns') !!}
                        {!! Form::text('closed_statuses') !!}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save</button>

            {!! Form::close() !!}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_cpy_32.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml
Template File: sources-sink-32.tmpl.c
*/
/*
 * @description
 * CWE: 121 Stack Based Buffer Overflow
 * BadSource:  Point data to a buffer that does not have space for a NULL terminator
 * GoodSource: Point data to a buffer that includes space for a NULL terminator
 * Sink: cpy
 *    BadSink : Copy string to data using strcpy()
 * Flow Variant: 32 Data flow using two pointers to the same value within the same function
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING "AAAAAAAAAA"

#ifndef OMITBAD

void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_cpy_32_bad()
{
    char * data;
    char * *dataPtr1 = &data;
    char * *dataPtr2 = &data;
    char dataBadBuffer[10];
    char dataGoodBuffer[10+1];
    {
        char * data = *dataPtr1;
        /* FLAW: Set a pointer to a buffer that does not leave room for a NULL terminator when performing
         * string copies in the sinks  */
        data = dataBadBuffer;
        data[0] = '\0'; /* null terminate */
        *dataPtr1 = data;
    }
    {
        char * data = *dataPtr2;
        {
            char source[10+1] = SRC_STRING;
            /* POTENTIAL FLAW: data may not have enough space to hold source */
            strcpy(data, source);
            printLine(data);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
    char * data;
    char * *dataPtr1 = &data;
    char * *dataPtr2 = &data;
    char dataBadBuffer[10];
    char dataGoodBuffer[10+1];
    {
        char * data = *dataPtr1;
        /* FIX: Set a pointer to a buffer that leaves room for a NULL terminator when performing
         * string copies in the sinks  */
        data = dataGoodBuffer;
        data[0] = '\0'; /* null terminate */
        *dataPtr1 = data;
    }
    {
        char * data = *dataPtr2;
        {
            char source[10+1] = SRC_STRING;
            /* POTENTIAL FLAW: data may not have enough space to hold source */
            strcpy(data, source);
            printLine(data);
        }
    }
}

void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_cpy_32_good()
{
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */
#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_cpy_32_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_cpy_32_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
.. _plugins-subclassing-publishable:

Subclassing Publishable
#######################

Due to the fact that ``Publishable`` is common Django model, it is possible to
simply extend it with your custom model. When doing this, you effectively adding
your custom model to **whole Ella machinery** and all publishing-related stuff
is ready for you out-of-the box!

Let's have a look at real-world example. During this walkthrough, we will try
to create a **publishable video** that will have YouTube *video code* as source.
We will keep it simple and use YouTube's video player to show the video itself.

The very first step is to create your own application using the standard Django
way:

.. code-block:: bash

    django-admin.py startapp video

After creating the app to hold it, let's define the class itself. If you are
acustomed to Django models, this is going to look very familiar to you.::

    # in models.py within your video application

    from __future__ import unicode_literals
    from django.db import models
    from django.utils.translation import ugettext_lazy as _
    from django.utils.encoding import force_text, python_2_unicode_compatible

    from ella.core.models import Publishable

    @python_2_unicode_compatible
    class YoutubeVideo(Publishable):
        code = models.CharField(max_length=20, title=_('Code'))

        class Meta:
            verbose_name = _('Youtube video')
            verbose_name_plural = _('Youtube videos')

        def __str__(self):
            return self.code

.. note::
    If you want to examine whats is going on behind the scenes when subclassing
    Django models, have a look at `Django model inheritance`_. We are using
    Multi-table inheritance so that each ``Publishable`` subclass has a hidden
    pointer - ``publishable_ptr`` - to the ``Publishable`` object. This pointer
    also acts as PK in the DB table.

Next step is to put the new app to the settings.::

    INSTALLED_APPS = (
        'ella.core',
        'ella.articles',
        ...
        'yourproject.video',
    )

Finally, resync your database so the DB table for the class is created:

.. code-block:: bash

    django-admin.py syncdb

By defining this, we already have a working publishable object, nothing more is
needed. Of course, in real world, you would probably need to do some polishing
(adding better title, etc.), but for now, this is enough.

.. _Django model inheritance: https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance


text:
import asyncio
import logging
import inspect
from copy import copy
from enum import Enum
from uuid import uuid4
from datetime import datetime, timezone

from tukio.event import EventSource, Event
from tukio.utils import FutureState, SkipTask
from tukio.broker import get_broker, workflow_exec_topics

from .task import TaskRegistry

log = logging.getLogger(__name__)

class TaskExecState(Enum):

    BEGIN = 'task-begin'
    END = 'task-end'
    ERROR = 'task-error'
    SKIP = 'task-skip'
    PROGRESS = 'task-progress'
    TIMEOUT = 'task-timeout'

    @classmethod
    def values(cls):
        return [member.value for member in cls]

    @classmethod
    def from_exception(cls, exc):
        if isinstance(exc, SkipTask):
            return cls.SKIP
        else:
            return cls.ERROR

class TukioTaskError(Exception):

    def __init__(self, output):
        self.task_outputs = output

class TukioTask(asyncio.Task):

    """
    A simple subclass of `asyncio.Task()` to add an execution ID and optionally
    bind a task holder class.
    """

    __slots__ = (
        'holder', 'uid', '_broker', '_in_progress', '_template', '_workflow',
        '_source', '_start', '_end', '_inputs', '_outputs', '_queue',
        '_commited', '_timed_out',
    )

    def __init__(self, coro, *, loop=None):
        super().__init__(coro, loop=loop)
        self.holder = inspect.getcoroutinelocals(coro).get('self')
        try:
            self.uid = self.holder.uid
        except AttributeError:
            self.uid = str(uuid4())
        self._broker = get_broker(self._loop)
        self._in_progress = False
        self._template = None
        self._workflow = None
        self._source = EventSource()
        self._start = None
        self._end = None
        self._inputs = None
        self._outputs = None
        self._queue = asyncio.Queue(loop=self._loop)
        if self.holder:
            self.holder.queue = self._queue
        # A 'committed' task is a pending task not suspended
        self._committed = asyncio.Event()
        self._committed.set()
        self._timed_out = False

    @property
    def inputs(self):
        return self._inputs

    @inputs.setter
    def inputs(self, data):
        # Freeze input data (dict or event)
        self._inputs = copy(data)

    @property
    def outputs(self):
        return self._outputs

    @property
    def template(self):
        return self._template

    @property
    def workflow(self):
        return self._workflow

    @property
    def event_source(self):
        return self._source

    @property
    def queue(self):
        return self._queue

    @property
    def committed(self):
        return self._committed.is_set()

    @property
    def timed_out(self):
        return self._timed_out

    def timeout(self):
        """
        Timeout the task, cancelling its execution.
        """
        self.cancel()
        self._timed_out = True

    def suspend(self):
        """
        Suspend a task means, for now, to cancel the task but flag it as
        'suspended'. It shall be executed from scratch upon workflow resume.

        TODO: improve this method to avoid cancelling the task but to actually
        suspend transactionnal jobs inside the task.
        """
        self.cancel()
        self._committed.clear()

    def as_dict(self):
        """
        Returns the execution informations of this task.
        """
        return {
            'id': self.uid,
            'start': self._start,
            'end': self._end,
            'state': FutureState.get(self).value,
            'inputs': self._inputs,
            'outputs': self._outputs
        }

    async def data_received(self, event):
        """
        A handler that puts events into the task's own receiving queue. This
        handler shall be registered in the data broker so that any tukio task
        can receive and process events during execution.
        """
        await self._queue.put(event)

    def in_progress(self):
        """
        Returns True if the task execution started, else returns False.
        """
        return self._in_progress

    def result(self):
        """
        Wrapper around `Future.result()` to automatically dispatch a
        `TaskExecState.END` or `TaskExecState.ERROR` event.
        """
        try:
            result = super().result()
        except asyncio.CancelledError:
            # The task was cancelled, simply raise it.
            if self._timed_out is False:
                raise
            # The task timed out, fetch the outputs and raise a TimeoutError.
            if self.holder:
                self._outputs = self.holder.teardown()
            # If teardown did not return anything, return inputs.
            if self._outputs is None:
                self._outputs = self._inputs
            self._end = datetime.now(timezone.utc)
            self._broker.dispatch(
                {'type': TaskExecState.TIMEOUT.value, 'content': self._outputs},
                topics=workflow_exec_topics(self._source._workflow_exec_id),
                source=self._source,
            )
            raise asyncio.TimeoutError
        except Exception as exc:
            self._end = datetime.now(timezone.utc)
            etype = TaskExecState.from_exception(exc)
            if isinstance(exc, TukioTaskError):
                content = exc.task_outputs
                self._outputs = content
            else:
                content = {'exception': exc}
            self._broker.dispatch(
                {'type': etype.value, 'content': content},
                topics=workflow_exec_topics(self._source._workflow_exec_id),
                source=self._source,
            )
            raise
        else:
            # Freeze output data (dict or event)
            self._outputs = copy(result)
            self._end = datetime.now(timezone.utc)
            self._broker.dispatch(
                {'type': TaskExecState.END.value, 'content': self._outputs},
                topics=workflow_exec_topics(self._source._workflow_exec_id),
                source=self._source,
            )
            return result

    def dispatch_progress(self, data, event_type=None):
        """
        Dispatch task progress events in the 'EXEC_TOPIC' from
        this tukio task.
        """
        if event_type is None:
            event_type = TaskExecState.PROGRESS.value
        event_data = {'type': event_type, 'content': data}
        self._broker.dispatch(
            event_data,
            topics=workflow_exec_topics(self._source._workflow_exec_id),
            source=self._source,
        )

    def setup_workflow(self, workflow, template):
        self._workflow = workflow
        self._template = template
        self._start = datetime.now(timezone.utc)
        source = {'task_exec_id': self.uid}
        if self._template:
            source['task_template_id'] = self._template.uid
        if self._workflow:
            source['workflow_template_id'] = self._workflow.template.uid
            source['workflow_exec_id'] = self._workflow.uid
        self._source = EventSource(**source)
        self._in_progress = True
        data = {
            'type': TaskExecState.BEGIN.value,
            'content': self._inputs
        }
        self._broker.dispatch(
            data,
            topics=workflow_exec_topics(self._source._workflow_exec_id),
            source=self._source,
        )

def tukio_factory(loop, coro):
    """
    A task factory for asyncio that creates `TukioTask()` instances for all
    coroutines registered as Tukio tasks and default `asyncio.Task()` instances
    for all others.
    """
    try:
        # Trigger exception if not valid
        TaskRegistry.codes()[coro.cr_code]
    except (KeyError, AttributeError):
        # When the coroutine is not a registered Tukio task or when `coro` is a
        # simple generator (e.g. upon calling `asyncio.wait()`)
        task = asyncio.Task(coro, loop=loop)
    else:
        task = TukioTask(coro, loop=loop)
    return task


text:
namespace SaveTheSnails.Web.Areas.Coordinators.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    using AutoMapper;
    using AutoMapper.QueryableExtensions;

    using SaveTheSnails.Data;
    using SaveTheSnails.Web.Controllers;
    using SaveTheSnails.Web.Areas.Coordinators.ViewModels;

    using Kendo.Mvc.UI;
    using Kendo.Mvc.Extensions;
    using SaveTheSnails.Data.Models;
    using SaveTheSnails.Web.Services;
    using SaveTheSnails.Common;

    public class MissionsController : BaseController
    {
        private SchedulerMissionService missionService;

        public MissionsController(IAppData data)
            : base(data)
        {
            this.missionService = new SchedulerMissionService(this.Data, this.CurrentUser);
        }

        public ActionResult Schedule()
        {
            return View();
        }

        public JsonResult Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(missionService.GetAll().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Create([DataSourceRequest] DataSourceRequest request, MissionViewModel mission)
        {
            if (ModelState.IsValid)
            {
                mission.CoordinatorID = this.Data.Coordinators.All()
                                        .FirstOrDefault(c => c.User.UserName == this.CurrentUser.UserName).Id;
                this.missionService.Insert(mission, ModelState);
            }

            return Json(new[] { mission }.ToDataSourceResult(request, ModelState));
        }

        public virtual ActionResult Update([DataSourceRequest] DataSourceRequest request, MissionViewModel meeting)
        {

            if (true)
            {
                Success("Test", true);

                 ModelState.AddModelError("update-error", "Нямате право");
                 ModelState.AddModelError("update-error2", "Нямате желание");
            }
            else
            {

                if (ModelState.IsValid)
                {
                    missionService.Update(meeting, ModelState);
                }
            }

            return Json(new[] { meeting }.ToDataSourceResult(request, ModelState));
        }

        public virtual JsonResult Destroy([DataSourceRequest] DataSourceRequest request, MissionViewModel meeting)
        {
            if (ModelState.IsValid)
            {
                missionService.Delete(meeting, ModelState);
            }

            return Json(new[] { meeting }.ToDataSourceResult(request, ModelState));
        }

        //TODO : add in Where clause if region of problem is the same with region of current user
        public ActionResult GetProblemsList()
        {
            if (User.IsInRole(GlobalConstants.AdminRole))
            {

            }

            var coordinatorRegion = this.Data.Coordinators.All()
                                                    .FirstOrDefault(c => c.User.UserName == this.CurrentUser.UserName).RegionID;

            var problems = this.Data.Problems.All()
                                        .Where(p => p.MissionID == null || p.Location.RegionID == coordinatorRegion)
                                        .Project().To<ProblemViewModel>();

            return Json(problems, JsonRequestBehavior.AllowGet);
        }

    }
}


text:
. ./utils.sh || exit 1

# vscode text application folders
if command -v code >/dev/null 2>&1; then
	code_name="code"
elif command -v code-insiders >/dev/null 2>&1; then
	code_name="code-insiders"
else
	printf "Visual Studio Code is not installed\n"
	exit 1
fi;

case "$(uname)" in
	Darwin*)
		if [ $code_name = "code" ]; then
			vscode_folder="${HOME}/Library/Application Support/Code"
		elif [ $code_name = "code-insiders" ]; then
			vscode_folder="${HOME}/Library/Application Support/Code - Insiders"
        else
			printf "Visual Studio Code is not installed\n"
			exit 1
		fi;
		;;
esac

if [ -z "$vscode_folder" ]; then
	printf "Visual Studio Code setup is not supported for this platform\n"
	exit 1
fi;

mkdir -p "$vscode_folder" || exit 1
old_settings_folder="${vscode_folder}/User"
mkdir -p "$old_settings_folder" || exit 1;
new_settings_folder="$(_get_fullname ./vscode)" || exit 1
settings_filename="settings.json"
keybindings_filename="keybindings.json"
old_settings_file="${old_settings_folder}/${settings_filename}"
old_keybindings_file="${old_settings_folder}/${keybindings_filename}"
new_settings_file="${new_settings_folder}/${settings_filename}"
new_keybindings_file="${new_settings_folder}/${keybindings_filename}"

_make_dir "$vscode_folder" || exit 1

# user settings
symlink_user_settings() {
    newfile="$1"
    oldfile="$2"
	printf "Linking file %s into %s\n" "$newfile" "$oldfile"
	ln -s "$newfile" "$oldfile" || exit 1
}

process_user_settings() {
    newfile="$1"
    oldfile="$2"
    filename="$(basename "$newfile" .json)"

    if [ -L "$oldfile" ]; then
	    printf "User %s are already symlinked\n" "$filename"
	    printf "You might want to check manually if this is the right %s for you and remove that symlink if that's not the case\n" "$filename"
    elif [ -r "$oldfile" ] && [ -f "$oldfile" ]; then
	    printf "User %s are already installed." "$filename"
	    printf " Would you like to override the existing user %s or not ? (y/n) " "$filename"
	    while true; do
	    	read -r reply
	    	case "$reply" in
	    	    [yY][eE][sS]|[yY])
	    			printf "Removing existing user %s\n" "$filename"
	    			rm -f "$oldfile"
	    			symlink_user_settings "$newfile" "$oldfile" || exit 1
	    			break
	    	        ;;
	    	    [nN][oO]|[nN])
	    			break
	    			;;
	    	    *)
	    	        printf "Please answer yes or no\n"
	    	        ;;
	    	esac
	    done
    else
	    symlink_user_settings "$newfile" "$oldfile" || exit 1
    fi
}

process_user_settings "$new_settings_file" "$old_settings_file" || exit 1
process_user_settings "$new_keybindings_file" "$old_keybindings_file" || exit 1

# install vscode extensions
vscode_extensions=./vscode/vscode_extensions.txt
_test_executable "$code_name" || exit 1
_parse_text_file "$vscode_extensions"	\
	| while read -r extension; do
		printf "Installing extension %s\n" "$extension"
        eval "$code_name --install-extension $extension" || exit 1
	done


text:
title: Runtime loading
last_updated: 2021-06-08
sidebar: netcdfJavaTutorial_sidebar
permalink: runtime_loading.html
toc: false
---
## Runtime Loading

These are the various classes that can be plugged in at runtime:

### Register an IOServiceProvider

1) The recommended way is to use the [Service Provider](https://docs.oracle.com/javase/tutorial/ext/basics/spi.html){:target="_blank"}
mechanism and include your IOSP in a JAR on the classpath, where it is dynamically loaded at runtime. In your
JAR, include a file named `META-INF/services/ucar.nc2.iosp.IOServiceProvider` containing the
name(s) of your implementations, eg:

~~~
ucar.nc2.iosp.fysat.Fysatiosp
ucar.nc2.iosp.gini.Giniiosp
~~~

2) Alternatively, from your code, register your IOSP by calling:

{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&registerIOSP %}
{% endcapture %}
{{ rmd | markdownify }}

In both cases, your class must implement `ucar.nc2.iosp.IOServiceProvider`.
When `NetcdfFiles.open()` is called, we call `getIosp()` and loop through the `IOServiceProvider` classes calling `isValidFile()` on each until one returns `true`. This method is fast and accurate to insure efficient registration.

### Register a CoordSystemBuilder:

From your code, register your `CoordSystemBuilder` by calling:

{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&registerCoordSystemBuilder %}
{% endcapture %}
{{ rmd | markdownify }}

The registered class must implement `ucar.nc2.dataset.CoordSystemFactory`. The `NetcdfDataset` is checked if it has a `Convention` attribute, and if so,
it is matched by `conventionName`. If not, loop through the `CoordSystemFactory` classes and call `findConventionByIsMine()` on each, until one returns `true`.
If none are found, use the default `_Coordinate` convention.

### Register a TransformBuilder:
{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&registerCoordTransBuilder %}
{% endcapture %}
{{ rmd | markdownify }}

The registered class must implement `ucar.nc2.internal.dataset.CoordTransformFactory`. The Coordinate Transform `Variable` must have the transform name as one of its parameters.

### Register a FeatureDatasetFactory:
{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&registerFeatureDatasetFactory %}
{% endcapture %}
{{ rmd | markdownify }}

The registered class must implement `ucar.nc2.ft.FeatureDatasetFactory`.

### Register a GRIB1 table:
{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&registerGRIBTable %}
{% endcapture %}
{{ rmd | markdownify }}

This registers a single table for the given center/subcenter/version.
See [GribTables](grib_tables.html) for more information about parameter tables.
*Note:* GRIB2 table handling is still being developed.

### Register a GRIB1 lookup table:
{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&registerGRIBLookupTable %}
{% endcapture %}
{{ rmd | markdownify }}

This registers one or more tables for different center/subcenter/versions.
See [GribTables](grib_tables.html)  for more information about lookup tables.
*Note:* GRIB2 table handling is still being developed.

### Register a BUFR Table lookup:
{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&registerBUFRTable %}
{% endcapture %}
{{ rmd | markdownify }}

The file must be a [BUFR table lookup file](bufr_tables.html).

### Register a `Filter` implementation:
Users-supplied filters must be provided using the [Service Provider](https://docs.oracle.com/javase/tutorial/ext/basics/spi.html){:target="_blank"}
mechanism and included in a JAR on the classpath, where it is dynamically loaded at runtime.
In your JAR, include a file named `META-INF/services/ucar.nc2.filter.FilterProvider` containing the name(s) of your implementations, eg:

~~~
ucar.nc2.filter.BloscFilter
ucar.nc2.filter.GZipFilter
~~~

Your `FilterProvider` classes must implement the `ucar.nc2.filter.FilterProvider` interface.
See [here](reading_zarr.html#implementing-a-filter) for details on implementing user-supplied filters.

## Runtime Configuration

Instead of calling the above routines in your code, you can pass the CDM library an XML configuration file.
Note that your application must call `ucar.nc2.util.xml.RuntimeConfigParser.read()`.

The configuration file looks like this:
~~~xml
 <?xml version='1.0' encoding='UTF-8'?>
 <runtimeConfig>
1) <ioServiceProvider  class='edu.univ.ny.stuff.FooFiles'/>
2) <coordSystemBuilderFactory convention='foo' class='test.Foo'/>
3) <coordTransformFactory name='atmos_ln_sigma_coordinates' type='vertical' class='my.stuff.atmosSigmaLog'/>
4) <featureDatasetFactory featureType='Point' class='gov.noaa.obscure.file.Flabulate'/>
5) <gribParameterTable edition='1' center='58' subcenter='-1' version='128'>C:/grib/tables/ons288.xml</gribParameterTable>
6) <gribParameterTableLookup edition='1'>C:/grib/tables/ncepLookup.txt</gribParameterTableLookup>
7) <bufrtable filename='C:/my/files/lookup.txt' />
8) <grib1Table strict='false'/>
9) <Netcdf4Clibrary>
     <libraryPath>/usr/local/lib</libraryPath>
     <libraryName>netcdf</libraryName>
     <useForReading>false</useForReading>
   </Netcdf4Clibrary>
</runtimeConfig>
~~~

1. Loads an `IOServiceProvider` with the given class name
2. Loads a `CoordSysBuilderIF` with the given class name, which looks for the given `Convention` attribute value.
3. Loads a `CoordTransformFactory` with the given class name, which looks for the given `transformName` in the dataset. The type must be vertical or projection.
4. Loads a `FeatureDatasetFactory` with the given class name which open `FeatureDatasets` of the given `featureType`.
5. Load a [GRIB-1 parameter table](grib_tables.html) (as of version 4.3)
6. Load a [GRIB-1 parameter table lookup](grib_tables.html#standard-table-mapping) (as of version 4.3)
7. Load a [BUFR table lookup](bufr_tables.html) file.
8. Turn [strict GRIB1 table handling](grib_tables.html#strict) off.
9. Configure how the [NetCDF-4 C library](netcdf4_c_library.html) is discovered and used.
    * `libraryPath`: The directory in which the native library is installed.
    * `libraryName`: The name of the native library. This will be used to locate the proper `.DLL`, `.SO`, or `.DYLIB` file within the `libraryPath` directory.
    * `useForReading`: By default, the native library is only used for writing NetCDF-4 files; a pure-Java layer is responsible for reading them.
    However, if this property is set to `true`, then it will be used for reading NetCDF-4 (and HDF5) files as well.

There are several ways pass the Runtime Configuration XML to the CDM library. From your application, you can pass a `java.io.InputStream` (or JDOM element) to
`ucar.nc2.util.xml.RuntimeConfigParser`, as in the following examples:

{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&passConfigurationToCDM %}
{% endcapture %}
{{ rmd | markdownify }}

For example, the ToolsUI application allows you to specify this file on the command line with the `-nj22Config` parameter:

{% capture rmd %}
{% includecodeblock netcdf-java&docs/src/test/java/examples/runtime/runtimeloadingTutorial.java&passConfigurationToolsUI %}
{% endcapture %}
{{ rmd | markdownify }}

If none is specified on the command line, it will look for the XML document in `$USER_HOME/.unidata/nj22Config.xml`.


text:
package com.vaadin.client.ui.orderedlayout;

import java.util.List;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ApplicationConnection;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ConnectorHierarchyChangeEvent;
import com.vaadin.client.LayoutManager;
import com.vaadin.client.Profiler;
import com.vaadin.client.ServerConnector;
import com.vaadin.client.TooltipInfo;
import com.vaadin.client.Util;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.communication.StateChangeEvent.StateChangeHandler;
import com.vaadin.client.ui.AbstractFieldConnector;
import com.vaadin.client.ui.AbstractLayoutConnector;
import com.vaadin.client.ui.Icon;
import com.vaadin.client.ui.LayoutClickEventHandler;
import com.vaadin.client.ui.aria.AriaHelper;
import com.vaadin.client.ui.layout.ElementResizeEvent;
import com.vaadin.client.ui.layout.ElementResizeListener;
import com.vaadin.shared.AbstractFieldState;
import com.vaadin.shared.ComponentConstants;
import com.vaadin.shared.communication.URLReference;
import com.vaadin.shared.ui.AlignmentInfo;
import com.vaadin.shared.ui.LayoutClickRpc;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.shared.ui.orderedlayout.AbstractOrderedLayoutServerRpc;
import com.vaadin.shared.ui.orderedlayout.AbstractOrderedLayoutState;

/**
 * Base class for vertical and horizontal ordered layouts
 */
public abstract class AbstractOrderedLayoutConnector extends
        AbstractLayoutConnector {

    /*
     * Handlers & Listeners
     */

    private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(
            this) {

        @Override
        protected ComponentConnector getChildComponent(
                com.google.gwt.user.client.Element element) {
            return Util.getConnectorForElement(getConnection(), getWidget(),
                    element);
        }

        @Override
        protected LayoutClickRpc getLayoutClickRPC() {
            return getRpcProxy(AbstractOrderedLayoutServerRpc.class);
        }
    };

    private StateChangeHandler childStateChangeHandler = new StateChangeHandler() {
        @Override
        public void onStateChanged(StateChangeEvent stateChangeEvent) {
            // Child state has changed, update stuff it hasn't already been done
            updateInternalState();

            /*
             * Some changes must always be done after each child's own state
             * change handler has been run because it might have changed some
             * styles that are overridden here.
             */
            ServerConnector child = stateChangeEvent.getConnector();
            if (child instanceof ComponentConnector) {
                ComponentConnector component = (ComponentConnector) child;
                Slot slot = getWidget().getSlot(component.getWidget());

                slot.setRelativeWidth(component.isRelativeWidth());
                slot.setRelativeHeight(component.isRelativeHeight());
            }
        }
    };

    private ElementResizeListener slotCaptionResizeListener = new ElementResizeListener() {
        @Override
        public void onElementResize(ElementResizeEvent e) {

            // Get all needed element references
            Element captionElement = e.getElement();

            // Caption position determines if the widget element is the first or
            // last child inside the caption wrap
            CaptionPosition pos = getWidget().getCaptionPositionFromElement(
                    captionElement.getParentElement());

            // The default is the last child
            Element widgetElement = captionElement.getParentElement()
                    .getLastChild().cast();

            // ...but if caption position is bottom or right, the widget is the
            // first child
            if (pos == CaptionPosition.BOTTOM || pos == CaptionPosition.RIGHT) {
                widgetElement = captionElement.getParentElement()
                        .getFirstChildElement().cast();
            }

            if (captionElement == widgetElement) {
                // Caption element already detached
                Slot slot = getWidget().getSlot(widgetElement);
                if (slot != null) {
                    slot.setCaptionResizeListener(null);
                }
                return;
            }

            String widgetWidth = widgetElement.getStyle().getWidth();
            String widgetHeight = widgetElement.getStyle().getHeight();

            if (widgetHeight.endsWith("%")
                    && (pos == CaptionPosition.TOP || pos == CaptionPosition.BOTTOM)) {
                getWidget().updateCaptionOffset(captionElement);
            } else if (widgetWidth.endsWith("%")
                    && (pos == CaptionPosition.LEFT || pos == CaptionPosition.RIGHT)) {
                getWidget().updateCaptionOffset(captionElement);
            }

            updateLayoutHeight();

            if (needsExpand()) {
                getWidget().updateExpandCompensation();
            }
        }
    };

    private ElementResizeListener childComponentResizeListener = new ElementResizeListener() {
        @Override
        public void onElementResize(ElementResizeEvent e) {
            updateLayoutHeight();
            if (needsExpand()) {
                getWidget().updateExpandCompensation();
            }
        }
    };

    private ElementResizeListener spacingResizeListener = new ElementResizeListener() {
        @Override
        public void onElementResize(ElementResizeEvent e) {
            if (needsExpand()) {
                getWidget().updateExpandCompensation();
            }
        }
    };

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.client.ui.AbstractComponentConnector#init()
     */
    @Override
    public void init() {
        super.init();
        getWidget().setLayoutManager(getLayoutManager());
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.client.ui.AbstractLayoutConnector#getState()
     */
    @Override
    public AbstractOrderedLayoutState getState() {
        return (AbstractOrderedLayoutState) super.getState();
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.client.ui.AbstractComponentConnector#getWidget()
     */
    @Override
    public VAbstractOrderedLayout getWidget() {
        return (VAbstractOrderedLayout) super.getWidget();
    }

    /**
     * Keep track of whether any child has relative height. Used to determine
     * whether measurements are needed to make relative child heights work
     * together with undefined container height.
     */
    private boolean hasChildrenWithRelativeHeight = false;

    /**
     * Keep track of whether any child has relative width. Used to determine
     * whether measurements are needed to make relative child widths work
     * together with undefined container width.
     */
    private boolean hasChildrenWithRelativeWidth = false;

    /**
     * Keep track of whether any child is middle aligned. Used to determine if
     * measurements are needed to make middle aligned children work.
     */
    private boolean hasChildrenWithMiddleAlignment = false;

    /**
     * Keeps track of whether slots should be expanded based on available space.
     */
    private boolean needsExpand = false;

    /**
     * The id of the previous response for which state changes have been
     * processed. If this is the same as the
     * {@link ApplicationConnection#getLastResponseId()}, it means that we can
     * skip some quite expensive calculations because we know that the state
     * hasn't changed since the last time the values were calculated.
     */
    private int processedResponseId = -1;

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.client.HasComponentsConnector#updateCaption(com.vaadin
     * .client.ComponentConnector)
     */
    @Override
    public void updateCaption(ComponentConnector connector) {
        /*
         * Don't directly update captions here to avoid calling e.g.
         * updateLayoutHeight() before everything is initialized.
         * updateInternalState() will ensure all captions are updated when
         * appropriate.
         */
        updateInternalState();
    }

    private void updateCaptionInternal(ComponentConnector child) {
        Slot slot = getWidget().getSlot(child.getWidget());

        String caption = child.getState().caption;
        URLReference iconUrl = child.getState().resources
                .get(ComponentConstants.ICON_RESOURCE);
        String iconUrlString = iconUrl != null ? iconUrl.getURL() : null;
        Icon icon = child.getConnection().getIcon(iconUrlString);

        List<String> styles = child.getState().styles;
        String error = child.getState().errorMessage;
        boolean showError = error != null;
        if (child.getState() instanceof AbstractFieldState) {
            AbstractFieldState abstractFieldState = (AbstractFieldState) child
                    .getState();
            showError = showError && !abstractFieldState.hideErrors;
        }
        boolean required = false;
        if (child instanceof AbstractFieldConnector) {
            required = ((AbstractFieldConnector) child).isRequired();
        }
        boolean enabled = child.isEnabled();

        if (slot.hasCaption() && null == caption) {
            slot.setCaptionResizeListener(null);
        }

        slot.setCaption(caption, icon, styles, error, showError, required,
                enabled, child.getState().captionAsHtml);

        AriaHelper.handleInputRequired(child.getWidget(), required);
        AriaHelper.handleInputInvalid(child.getWidget(), showError);
        AriaHelper.bindCaption(child.getWidget(), slot.getCaptionElement());

        if (slot.hasCaption()) {
            CaptionPosition pos = slot.getCaptionPosition();
            slot.setCaptionResizeListener(slotCaptionResizeListener);
            if (child.isRelativeHeight()
                    && (pos == CaptionPosition.TOP || pos == CaptionPosition.BOTTOM)) {
                getWidget().updateCaptionOffset(slot.getCaptionElement());
            } else if (child.isRelativeWidth()
                    && (pos == CaptionPosition.LEFT || pos == CaptionPosition.RIGHT)) {
                getWidget().updateCaptionOffset(slot.getCaptionElement());
            }
        }

    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.client.ui.AbstractComponentContainerConnector#
     * onConnectorHierarchyChange
     * (com.vaadin.client.ConnectorHierarchyChangeEvent)
     */
    @Override
    public void onConnectorHierarchyChange(ConnectorHierarchyChangeEvent event) {
        Profiler.enter("AOLC.onConnectorHierarchyChange");

        List<ComponentConnector> previousChildren = event.getOldChildren();
        int currentIndex = 0;
        VAbstractOrderedLayout layout = getWidget();

        // remove spacing as it is exists as separate elements that cannot be
        // removed easily after reordering the contents
        Profiler.enter("AOLC.onConnectorHierarchyChange temporarily remove spacing");
        layout.setSpacing(false);
        Profiler.leave("AOLC.onConnectorHierarchyChange temporarily remove spacing");

        for (ComponentConnector child : getChildComponents()) {
            Profiler.enter("AOLC.onConnectorHierarchyChange add children");
            Slot slot = layout.getSlot(child.getWidget());
            if (slot.getParent() != layout) {
                Profiler.enter("AOLC.onConnectorHierarchyChange add state change handler");
                child.addStateChangeHandler(childStateChangeHandler);
                Profiler.leave("AOLC.onConnectorHierarchyChange add state change handler");
            }
            Profiler.enter("AOLC.onConnectorHierarchyChange addOrMoveSlot");
            layout.addOrMoveSlot(slot, currentIndex++, false);
            Profiler.leave("AOLC.onConnectorHierarchyChange addOrMoveSlot");

            Profiler.leave("AOLC.onConnectorHierarchyChange add children");
        }

        // re-add spacing for the elements that should have it
        Profiler.enter("AOLC.onConnectorHierarchyChange setSpacing");
        // spacings were removed above
        if (getState().spacing) {
            layout.setSpacing(true);
        }
        Profiler.leave("AOLC.onConnectorHierarchyChange setSpacing");

        for (ComponentConnector child : previousChildren) {
            Profiler.enter("AOLC.onConnectorHierarchyChange remove children");
            if (child.getParent() != this) {
                Slot slot = layout.getSlot(child.getWidget());
                slot.setWidgetResizeListener(null);
                if (slot.hasCaption()) {
                    slot.setCaptionResizeListener(null);
                }
                slot.setSpacingResizeListener(null);
                child.removeStateChangeHandler(childStateChangeHandler);
                layout.removeWidget(child.getWidget());
            }
            Profiler.leave("AOLC.onConnectorHierarchyChange remove children");
        }
        Profiler.leave("AOLC.onConnectorHierarchyChange");

        updateInternalState();
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.vaadin.client.ui.AbstractComponentConnector#onStateChanged(com.vaadin
     * .client.communication.StateChangeEvent)
     */
    @Override
    public void onStateChanged(StateChangeEvent stateChangeEvent) {
        super.onStateChanged(stateChangeEvent);

        clickEventHandler.handleEventHandlerRegistration();
        getWidget().setMargin(new MarginInfo(getState().marginsBitmask));
        getWidget().setSpacing(getState().spacing);

        updateInternalState();
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.vaadin.client.ui.AbstractComponentConnector#getTooltipInfo(com.google
     * .gwt.dom.client.Element)
     */
    @Override
    public TooltipInfo getTooltipInfo(com.google.gwt.dom.client.Element element) {
        if (element != getWidget().getElement()) {
            Slot slot = WidgetUtil.findWidget(element, Slot.class);
            if (slot != null && slot.getCaptionElement() != null
                    && slot.getParent() == getWidget()
                    && slot.getCaptionElement().isOrHasChild(element)) {
                ComponentConnector connector = Util.findConnectorFor(slot
                        .getWidget());
                if (connector != null) {
                    return connector.getTooltipInfo(element);
                }
            }
        }
        return super.getTooltipInfo(element);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.client.ui.AbstractComponentConnector#hasTooltip()
     */
    @Override
    public boolean hasTooltip() {
        /*
         * Tooltips are fetched from child connectors -> there's no quick way of
         * checking whether there might a tooltip hiding somewhere
         */
        return true;
    }

    /**
     * Updates DOM properties and listeners based on the current state of this
     * layout and its children.
     */
    private void updateInternalState() {
        // Avoid updating again for the same data
        int lastResponseId = getConnection().getLastResponseId();
        if (processedResponseId == lastResponseId) {
            return;
        }
        Profiler.enter("AOLC.updateInternalState");
        // Remember that everything is updated for this response
        processedResponseId = lastResponseId;

        hasChildrenWithRelativeHeight = false;
        hasChildrenWithRelativeWidth = false;

        hasChildrenWithMiddleAlignment = false;

        needsExpand = getWidget().vertical ? !isUndefinedHeight()
                : !isUndefinedWidth();

        boolean onlyZeroExpands = true;
        if (needsExpand) {
            for (ComponentConnector child : getChildComponents()) {
                double expandRatio = getState().childData.get(child).expandRatio;
                if (expandRatio != 0) {
                    onlyZeroExpands = false;
                    break;
                }
            }
        }

        // First update bookkeeping for all children
        for (ComponentConnector child : getChildComponents()) {
            Slot slot = getWidget().getSlot(child.getWidget());

            slot.setRelativeWidth(child.isRelativeWidth());
            slot.setRelativeHeight(child.isRelativeHeight());

            if (child.delegateCaptionHandling()) {
                updateCaptionInternal(child);
            }

            // Update slot style names
            List<String> childStyles = child.getState().styles;
            if (childStyles == null) {
                getWidget().setSlotStyleNames(child.getWidget(),
                        (String[]) null);
            } else {
                getWidget().setSlotStyleNames(child.getWidget(),
                        childStyles.toArray(new String[childStyles.size()]));
            }

            AlignmentInfo alignment = new AlignmentInfo(
                    getState().childData.get(child).alignmentBitmask);
            slot.setAlignment(alignment);

            if (alignment.isVerticalCenter()) {
                hasChildrenWithMiddleAlignment = true;
            }

            double expandRatio = onlyZeroExpands ? 1 : getState().childData
                    .get(child).expandRatio;

            slot.setExpandRatio(expandRatio);

            if (child.isRelativeHeight()) {
                hasChildrenWithRelativeHeight = true;
            }
            if (child.isRelativeWidth()) {
                hasChildrenWithRelativeWidth = true;
            }
        }

        if (needsFixedHeight()) {
            // Add resize listener to ensure the widget itself is measured
            getLayoutManager().addElementResizeListener(
                    getWidget().getElement(), childComponentResizeListener);
        } else {
            getLayoutManager().removeElementResizeListener(
                    getWidget().getElement(), childComponentResizeListener);
        }

        // Then update listeners based on bookkeeping
        updateAllSlotListeners();

        // Update the layout at this point to ensure it's OK even if we get no
        // element resize events
        updateLayoutHeight();
        if (needsExpand()) {
            getWidget().updateExpandedSizes();
            // updateExpandedSizes causes fixed size components to temporarily
            // lose their size. updateExpandCompensation must be delayed until
            // the browser has a chance to measure them.
            Scheduler.get().scheduleFinally(new ScheduledCommand() {
                @Override
                public void execute() {
                    getWidget().updateExpandCompensation();
                }
            });
        } else {
            getWidget().clearExpand();
        }

        Profiler.leave("AOLC.updateInternalState");
    }

    /**
     * Does the layout need a fixed height?
     */
    private boolean needsFixedHeight() {
        boolean isVertical = getWidget().vertical;

        if (isVertical) {
            // Doesn't need height fix for vertical layouts
            return false;
        }

        else if (!isUndefinedHeight()) {
            // Fix not needed unless the height is undefined
            return false;
        }

        else if (!hasChildrenWithRelativeHeight
                && !hasChildrenWithMiddleAlignment) {
            // Already works if there are no relative heights or middle aligned
            // children
            return false;
        }

        return true;
    }

    /**
     * Does the layout need to expand?
     */
    private boolean needsExpand() {
        return needsExpand;
    }

    /**
     * Add slot listeners
     */
    private void updateAllSlotListeners() {
        for (ComponentConnector child : getChildComponents()) {
            updateSlotListeners(child);
        }
    }

    /**
     * Add/remove necessary ElementResizeListeners for one slot. This should be
     * called after each update to the slot's or it's widget.
     */
    private void updateSlotListeners(ComponentConnector child) {
        Slot slot = getWidget().getSlot(child.getWidget());

        // Clear all possible listeners first
        slot.setWidgetResizeListener(null);
        if (slot.hasCaption()) {
            slot.setCaptionResizeListener(null);
        }
        if (slot.hasSpacing()) {
            slot.setSpacingResizeListener(null);
        }

        // Add all necessary listeners
        if (needsFixedHeight()) {
            slot.setWidgetResizeListener(childComponentResizeListener);
            if (slot.hasCaption()) {
                slot.setCaptionResizeListener(slotCaptionResizeListener);
            }
        } else if ((hasChildrenWithRelativeHeight || hasChildrenWithRelativeWidth)
                && slot.hasCaption()) {
            /*
             * If the slot has caption, we need to listen for its size changes
             * in order to update the padding/margin offset for relative sized
             * components.
             *
             * TODO might only be needed if the caption is in the same direction
             * as the relative size?
             */
            slot.setCaptionResizeListener(slotCaptionResizeListener);
        }

        if (needsExpand()) {
            // TODO widget resize only be needed for children without expand?
            slot.setWidgetResizeListener(childComponentResizeListener);
            if (slot.hasSpacing()) {
                slot.setSpacingResizeListener(spacingResizeListener);
            }
        }
    }

    /**
     * Re-calculate the layout height
     */
    private void updateLayoutHeight() {
        if (needsFixedHeight()) {
            int h = getMaxHeight();
            if (h < 0) {
                // Postpone change if there are elements that have not yet been
                // measured
                return;
            }
            h += getLayoutManager().getBorderHeight(getWidget().getElement())
                    + getLayoutManager().getPaddingHeight(
                            getWidget().getElement());
            getWidget().getElement().getStyle().setHeight(h, Unit.PX);
            getLayoutManager().setNeedsMeasure(this);
        }
    }

    /**
     * Measures the maximum height of the layout in pixels
     */
    private int getMaxHeight() {
        int highestNonRelative = -1;
        int highestRelative = -1;

        LayoutManager layoutManager = getLayoutManager();

        for (ComponentConnector child : getChildComponents()) {
            Widget childWidget = child.getWidget();
            Slot slot = getWidget().getSlot(childWidget);
            Element captionElement = slot.getCaptionElement();
            CaptionPosition captionPosition = slot.getCaptionPosition();

            int pixelHeight = layoutManager.getOuterHeight(childWidget
                    .getElement());
            if (pixelHeight == -1) {
                // Height has not yet been measured -> postpone actions that
                // depend on the max height
                return -1;
            }

            boolean hasRelativeHeight = slot.hasRelativeHeight();

            boolean captionSizeShouldBeAddedtoComponentHeight = captionPosition == CaptionPosition.TOP
                    || captionPosition == CaptionPosition.BOTTOM;
            boolean includeCaptionHeight = captionElement != null
                    && captionSizeShouldBeAddedtoComponentHeight;

            if (includeCaptionHeight) {
                int captionHeight = layoutManager
                        .getOuterHeight(captionElement)
                        - getLayoutManager().getMarginHeight(captionElement);
                if (captionHeight == -1) {
                    // Height has not yet been measured -> postpone actions that
                    // depend on the max height
                    return -1;
                }
                pixelHeight += captionHeight;
            }

            if (!hasRelativeHeight) {
                if (pixelHeight > highestNonRelative) {
                    highestNonRelative = pixelHeight;
                }
            } else {
                if (pixelHeight > highestRelative) {
                    highestRelative = pixelHeight;
                }
            }
        }
        return highestNonRelative > -1 ? highestNonRelative : highestRelative;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.client.ui.AbstractComponentConnector#onUnregister()
     */
    @Override
    public void onUnregister() {
        // Cleanup all ElementResizeListeners
        for (ComponentConnector child : getChildComponents()) {
            Slot slot = getWidget().getSlot(child.getWidget());
            if (slot.hasCaption()) {
                slot.setCaptionResizeListener(null);
            }

            if (slot.getSpacingElement() != null) {
                slot.setSpacingResizeListener(null);
            }

            slot.setWidgetResizeListener(null);
        }

        super.onUnregister();
    }
}


text:
#ifndef NEWSBOAT_FRESHRSSURLREADER_H_
#define NEWSBOAT_FRESHRSSURLREADER_H_

#include "urlreader.h"

namespace newsboat {

class ConfigContainer;
class RemoteApi;

class FreshRssUrlReader : public UrlReader {
public:
	FreshRssUrlReader(ConfigContainer* c,
		const std::string& url_file,
		RemoteApi* a);
	~FreshRssUrlReader() override;
	nonstd::optional<utils::ReadTextFileError> reload() override;
	std::string get_source() override;

private:
	ConfigContainer* cfg;
	std::string file;
	RemoteApi* api;
};

} // namespace newsboat

#endif /* NEWSBOAT_FRESHRSSURLREADER_H_ */


text:
from decimal import Decimal as D

from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _

from oscar.core.loading import get_class, get_model

from . import exceptions

Order = get_model('order', 'Order')
Line = get_model('order', 'Line')
OrderDiscount = get_model('order', 'OrderDiscount')
order_placed = get_class('order.signals', 'order_placed')

class OrderNumberGenerator(object):

    """
    Simple object for generating order numbers.

    We need this as the order number is often required for payment
    which takes place before the order model has been created.
    """

    def order_number(self, basket):
        """
        Return an order number for a given basket
        """
        return 100000 + basket.id

class OrderCreator(object):

    """
    Places the order by writing out the various models
    """

    def place_order(self, basket, total,  # noqa (too complex (12))
                    shipping_method, shipping_charge, user=None,
                    shipping_address=None, billing_address=None,
                    order_number=None, status=None, **kwargs):
        """
        Placing an order involves creating all the relevant models based on the
        basket and session data.
        """
        if basket.is_empty:
            raise ValueError(_("Empty baskets cannot be submitted"))
        if not order_number:
            generator = OrderNumberGenerator()
            order_number = generator.order_number(basket)
        if not status and hasattr(settings, 'OSCAR_INITIAL_ORDER_STATUS'):
            status = getattr(settings, 'OSCAR_INITIAL_ORDER_STATUS')
        try:
            Order._default_manager.get(number=order_number)
        except Order.DoesNotExist:
            pass
        else:
            raise ValueError(_("There is already an order with number %s")
                             % order_number)

        # Ok - everything seems to be in order, let's place the order
        order = self.create_order_model(
            user, basket, shipping_address, shipping_method, shipping_charge,
            billing_address, total, order_number, status, **kwargs)
        for line in basket.all_lines():
            self.create_line_models(order, line)
            self.update_stock_records(line)

        # Record any discounts associated with this order
        for application in basket.offer_applications:
            # Trigger any deferred benefits from offers and capture the
            # resulting message
            application['message'] \
                = application['offer'].apply_deferred_benefit(basket, order,
                                                              application)
            # Record offer application results
            if application['result'].affects_shipping:
                # Skip zero shipping discounts
                shipping_discount = shipping_method.discount(basket)
                if shipping_discount <= D('0.00'):
                    continue
                # If a shipping offer, we need to grab the actual discount off
                # the shipping method instance, which should be wrapped in an
                # OfferDiscount instance.
                application['discount'] = shipping_discount
            self.create_discount_model(order, application)
            self.record_discount(application)

        for voucher in basket.vouchers.all():
            self.record_voucher_usage(order, voucher, user)

        # Send signal for analytics to pick up
        order_placed.send(sender=self, order=order, user=user)

        return order

    def create_order_model(self, user, basket, shipping_address,
                           shipping_method, shipping_charge, billing_address,
                           total, order_number, status, **extra_order_fields):
        """
        Create an order model.
        """
        order_data = {'basket': basket,
                      'number': order_number,
                      'site': Site._default_manager.get_current(),
                      'currency': total.currency,
                      'total_incl_tax': total.incl_tax,
                      'total_excl_tax': total.excl_tax,
                      'shipping_incl_tax': shipping_charge.incl_tax,
                      'shipping_excl_tax': shipping_charge.excl_tax,
                      'shipping_method': shipping_method.name,
                      'shipping_code': shipping_method.code}
        if shipping_address:
            order_data['shipping_address'] = shipping_address
        if billing_address:
            order_data['billing_address'] = billing_address
        if user and user.is_authenticated():
            order_data['user_id'] = user.id
        if status:
            order_data['status'] = status
        if extra_order_fields:
            order_data.update(extra_order_fields)
        order = Order(**order_data)
        order.save()
        return order

    def create_line_models(self, order, basket_line, extra_line_fields=None):
        """
        Create the batch line model.

        You can set extra fields by passing a dictionary as the
        extra_line_fields value
        """
        product = basket_line.product
        stockrecord = None

        if basket_line.product.get_product_class().track_stock:
            stockrecord = basket_line.stockrecord
            if not stockrecord:
                raise exceptions.UnableToPlaceOrder(
                    "Baket line #%d has no stockrecord" % basket_line.id)

        line_data = {
            'order': order
        }

        if stockrecord:

            partner = stockrecord.partner
            line_data.update({
                # Partner details
                'partner': partner,
                'partner_name': partner.name,
                'partner_sku': stockrecord.partner_sku,
                # Reporting details
                'unit_cost_price': stockrecord.cost_price,
                'unit_retail_price': stockrecord.price_retail,
            })

        line_data.update({
            # Product details
            'product': product,
            'title': product.get_title(),
            'upc': product.upc,
            'quantity': basket_line.quantity,
            # Price details
            'line_price_excl_tax':
            basket_line.line_price_excl_tax_incl_discounts,
            'line_price_incl_tax':
            basket_line.line_price_incl_tax_incl_discounts,
            'line_price_before_discounts_excl_tax':
            basket_line.line_price_excl_tax,
            'line_price_before_discounts_incl_tax':
            basket_line.line_price_incl_tax,
            # Reporting details
            'unit_price_incl_tax': basket_line.unit_price_incl_tax,
            'unit_price_excl_tax': basket_line.unit_price_excl_tax,
            # Shipping details
            'est_dispatch_date':
            basket_line.purchase_info.availability.dispatch_date
        })
        extra_line_fields = extra_line_fields or {}
        if hasattr(settings, 'OSCAR_INITIAL_LINE_STATUS'):
            if not (extra_line_fields and 'status' in extra_line_fields):
                extra_line_fields['status'] = getattr(
                    settings, 'OSCAR_INITIAL_LINE_STATUS')
        if extra_line_fields:
            line_data.update(extra_line_fields)

        order_line = Line._default_manager.create(**line_data)
        self.create_line_price_models(order, order_line, basket_line)
        self.create_line_attributes(order, order_line, basket_line)
        self.create_additional_line_models(order, order_line, basket_line)

        return order_line

    def update_stock_records(self, line):
        """
        Update any relevant stock records for this order line
        """
        if line.product.get_product_class().track_stock:
            line.stockrecord.allocate(line.quantity)

    def create_additional_line_models(self, order, order_line, basket_line):
        """
        Empty method designed to be overridden.

        Some applications require additional information about lines, this
        method provides a clean place to create additional models that
        relate to a given line.
        """
        pass

    def create_line_price_models(self, order, order_line, basket_line):
        """
        Creates the batch line price models
        """
        breakdown = basket_line.get_price_breakdown()
        for price_incl_tax, price_excl_tax, quantity in breakdown:
            order_line.prices.create(
                order=order,
                quantity=quantity,
                price_incl_tax=price_incl_tax,
                price_excl_tax=price_excl_tax)

    def create_line_attributes(self, order, order_line, basket_line):
        """
        Creates the batch line attributes.
        """
        for attr in basket_line.attributes.all():
            order_line.attributes.create(
                option=attr.option,
                type=attr.option.code,
                value=attr.value)

    def create_discount_model(self, order, discount):
        """
        Create an order discount model for each offer application attached to
        the basket.
        """
        order_discount = OrderDiscount(
            order=order,
            message=discount['message'] or '',
            offer_id=discount['offer'].id,
            frequency=discount['freq'],
            amount=discount['discount'])
        result = discount['result']
        if result.affects_shipping:
            order_discount.category = OrderDiscount.SHIPPING
        elif result.affects_post_order:
            order_discount.category = OrderDiscount.DEFERRED
        voucher = discount.get('voucher', None)
        if voucher:
            order_discount.voucher_id = voucher.id
            order_discount.voucher_code = voucher.code
        order_discount.save()

    def record_discount(self, discount):
        discount['offer'].record_usage(discount)
        if 'voucher' in discount and discount['voucher']:
            discount['voucher'].record_discount(discount)

    def record_voucher_usage(self, order, voucher, user):
        """
        Updates the models that care about this voucher.
        """
        voucher.record_usage(order, user)


text:
import React from 'react';
import { parse } from 'react-docgen';
import CodeExample from '../../../components/CodeExample';
import ComponentHeader from '../../../components/ComponentHeader';
import PropTypeDescription from '../../../components/PropTypeDescription';

import Demo from './Demo';
// eslint-disable-next-line
import demoCode from '!raw-loader!./Demo';
// eslint-disable-next-line
import componentCode from '!raw-loader!ringcentral-widgets/components/ContactsView';

const ContactsViewPage = () => {
  const info = parse(componentCode);
  return (
    <div>
      <ComponentHeader name="ContactsView" description={info.description} />
      <CodeExample code={demoCode} title="ContactsView Example">
        <Demo />
      </CodeExample>
      <PropTypeDescription componentInfo={info} />
    </div>
  );
};

export default ContactsViewPage;


text:
import chai from 'chai'
import {openQuestionnaire} from '../helpers'

import EstablishmentType from '../pages/surveys/census/communal/establishment-type.page.js'
import BedSpaces from '../pages/surveys/census/communal/bed-spaces.page.js'
import UsualResidents from '../pages/surveys/census/communal/usual-residents.page.js'
import UsualResidentsNumber from '../pages/surveys/census/communal/usual-residents-number.page.js'
import DescribeResidents from '../pages/surveys/census/communal/describe-residents.page.js'
import CompletionPreferenceIndividual from '../pages/surveys/census/communal/completion-preference-individual.page.js'
import WhyPaperIndividual from '../pages/surveys/census/communal/why-paper-individual.page.js'
import CompletionPreferenceEstablishment from '../pages/surveys/census/communal/completion-preference-establishment.page.js'
import WhyPaperEstablishment from '../pages/surveys/census/communal/why-paper-establishment.page.js'
import FurtherContact from '../pages/surveys/census/communal/further-contact.page.js'
import ContactDetails from '../pages/surveys/census/communal/contact-details.page.js'
import Confirmation from '../pages/confirmation.page.js'
import ThankYou from '../pages/thank-you.page'

const expect = chai.expect

describe('Example Test', function() {

  it('Given Respondent Home has identified the respondent should have the Communal Establishment Questionnaire, When I complete the EQ, Then i should be able to successfully submit', function() {
      openQuestionnaire('census_communal.json')

      EstablishmentType.clickEstablishmentTypeAnswerHotel().submit()
      BedSpaces.setBedSpacesAnswer(20).submit()
      UsualResidents.clickUsualResidentsAnswerYes().submit()
      UsualResidentsNumber.setUsualResidentsNumberAnswer(10).submit()
      DescribeResidents.clickDescribeResidentsAnswerPayingGuests().submit()
      CompletionPreferenceIndividual.clickCompletionPreferenceIndividualAnswerPaper().submit()
      WhyPaperIndividual.clickWhyPaperIndividualAnswerUnsureHowToUseAComputer().submit()
      CompletionPreferenceEstablishment.clickCompletionPreferenceEstablishmentAnswerPaper().submit()
      WhyPaperEstablishment.clickWhyPaperEstablishmentAnswerMoreConvenient().submit()
      FurtherContact.clickFurtherContactAnswerYes().submit()
      ContactDetails.setContactDetailsAnswerName("John Smith").setContactDetailsAnswerEmail("jon@smith.com").setContactDetailsAnswerPhone("098765432347").submit()

      Confirmation.submit()

      // Thank You
      expect(ThankYou.isOpen()).to.be.true
  })

  it('Given Respondent Home has identified the respondent should have the Communal Establishment Questionnaire, When I complete the EQ with 0 bed spaces, Then i should be routed to further contact', function() {
      openQuestionnaire('census_communal.json')

      EstablishmentType.clickEstablishmentTypeAnswerHotel().submit()
      BedSpaces.setBedSpacesAnswer(0).submit()
      FurtherContact.clickFurtherContactAnswerYes().submit()
      ContactDetails.setContactDetailsAnswerName("John Smith").setContactDetailsAnswerEmail("jon@smith.com").setContactDetailsAnswerPhone("098765432347").submit()

      Confirmation.submit()

      // Thank You
      expect(ThankYou.isOpen()).to.be.true
  })

  it('Given I am completing the Communal Establishment questionnaire, When I answer No to the Usual Residents question, Then I should be routed to Completion Preferences', function() {

      // Given I am completing the Communal Establishment questionnaire,
      openQuestionnaire('census_communal.json')

      EstablishmentType.clickEstablishmentTypeAnswerHotel().submit()
      BedSpaces.setBedSpacesAnswer(2).submit()

      // When I answer No to the Usual Residents question
      UsualResidents.clickUsualResidentsAnswerNo().submit()

      // Then I should be routed to Completion Preferences
      expect(CompletionPreferenceEstablishment.isOpen()).to.equal(true, 'Expecting to be on Completion Preferences page')
  })

})


text:
package org.apereo.openlrs.storage.redis;

import org.apereo.openlrs.exceptions.InvalidEventFormatException;
import org.apereo.openlrs.model.OpenLRSEntity;
import org.apereo.openlrs.model.caliper.CaliperEvent;
import org.apereo.openlrs.model.xapi.Statement;
import org.apereo.openlrs.storage.StorageFactory;
import org.apereo.openlrs.storage.TierTwoStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author ggilbert
 *
 */
@Component
@Profile("redis")
public class RedisPubSubTierTwoMessageReceiver {

	private Logger log = LoggerFactory
			.getLogger(RedisPubSubTierTwoMessageReceiver.class);
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private StorageFactory storageFactory;

	public void onMessage(String json) {
		// guess at format
		OpenLRSEntity entity = null;

		try {
			entity = objectMapper.readValue(json.getBytes(), Statement.class);
		} catch (Exception e) {
			log.warn("unable to parse {} as xapi", json);
		}

		if (entity == null) {
			// try caliper
			try {
				entity = objectMapper.readValue(json.getBytes(),
						CaliperEvent.class);
			} catch (Exception e) {
				throw new InvalidEventFormatException(String.format(
						"unable to parse %s", json), e);
			}
		}

		try {
			TierTwoStorage<OpenLRSEntity> tierTwoStorage = storageFactory
					.getTierTwoStorage();
			tierTwoStorage.save(entity);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

	}

}