text:
const { expect } = require('chai');
const JDLObject = require('../../../jdl/models/jdl-object');
const JDLEntity = require('../../../jdl/models/jdl-entity');
const JDLField = require('../../../jdl/models/jdl-field');
const JDLValidation = require('../../../jdl/models/jdl-validation');
const JDLRelationship = require('../../../jdl/models/jdl-relationship');
const JDLBinaryOption = require('../../../jdl/models/jdl-binary-option');
const ApplicationTypes = require('../../../jdl/jhipster/application-types');
const DatabaseTypes = require('../../../jdl/jhipster/database-types');
const FieldTypes = require('../../../jdl/jhipster/field-types');
const Validations = require('../../../jdl/jhipster/validations');
const RelationshipTypes = require('../../../jdl/jhipster/relationship-types');
const BinaryOptions = require('../../../jdl/jhipster/binary-options');
const { createValidator } = require('../../../jdl/validators/jdl-without-application-validator');

describe('JDLWithoutApplicationValidator', () => {
  describe('createValidator', () => {
    context('when not passing a JDL object', () => {
      it('should fail', () => {
        expect(() => createValidator()).to.throw(/^A JDL object must be passed to check for business errors.$/);
      });
    });
  });
  describe('checkForErrors', () => {
    context('when having an entity with a reserved name', () => {
      let validator;

      before(() => {
        const jdlObject = new JDLObject();
        jdlObject.addEntity(
          new JDLEntity({
            name: 'Continue',
          })
        );
        validator = createValidator(jdlObject, { databaseType: DatabaseTypes.SQL });
      });

      it('should fail', () => {
        expect(() => {
          validator.checkForErrors();
        }).to.throw(/^The name 'Continue' is a reserved keyword and can not be used as an entity class name.$/);
      });
    });
    context('when having an entity with a reserved table name', () => {
      let parameter;

      before(() => {
        const jdlObject = new JDLObject();
        jdlObject.addEntity(
          new JDLEntity({
            name: 'valid',
            tableName: 'continue',
          })
        );
        const logger = {
          warn: callParameter => {
            parameter = callParameter;
          },
        };
        const validator = createValidator(
          jdlObject,
          {
            databaseType: DatabaseTypes.SQL,
          },
          logger
        );
        validator.checkForErrors();
      });

      it('should warn', () => {
        expect(parameter).to.equal(
          "The table name 'continue' is a reserved keyword, so it will be prefixed with the value of 'jhiPrefix'."
        );
      });
    });
    context('when having a field reserved name', () => {
      let parameter;

      before(() => {
        const jdlObject = new JDLObject();
        const entity = new JDLEntity({
          name: 'Valid',
        });
        entity.addField(
          new JDLField({
            name: 'catch',
            type: FieldTypes.CommonDBTypes.STRING,
          })
        );
        jdlObject.addEntity(entity);
        const logger = {
          warn: callParameter => {
            parameter = callParameter;
          },
        };
        const validator = createValidator(
          jdlObject,
          {
            databaseType: DatabaseTypes.SQL,
          },
          logger
        );
        validator.checkForErrors();
      });

      it('should warn', () => {
        expect(parameter).to.equal("The name 'catch' is a reserved keyword, so it will be prefixed with the value of 'jhiPrefix'.");
      });
    });
    context('when passing gateway as application type', () => {
      context('with incompatible database type and field type', () => {
        let validator;

        before(() => {
          const validEntity = new JDLEntity({
            name: 'Valid',
          });
          validEntity.addField(
            new JDLField({
              name: 'validField',
              type: 'UNKNOWN-TYPE',
            })
          );
          const jdlObject = new JDLObject();
          jdlObject.addEntity(validEntity);
          validator = createValidator(jdlObject, {
            databaseType: DatabaseTypes.SQL,
            applicationType: ApplicationTypes.GATEWAY,
          });
        });

        it('should not fail', () => {
          expect(() => {
            validator.checkForErrors();
          }).not.to.throw();
        });
      });
    });
    context('when having a field type that is invalid for a database type', () => {
      let validator;

      before(() => {
        const validEntity = new JDLEntity({
          name: 'Valid',
        });
        validEntity.addField(
          new JDLField({
            name: 'validField',
            type: 'WeirdType',
          })
        );
        const jdlObject = new JDLObject();
        jdlObject.addEntity(validEntity);
        validator = createValidator(jdlObject, {
          databaseType: DatabaseTypes.SQL,
        });
      });

      it('should fail', () => {
        expect(() => {
          validator.checkForErrors();
        }).to.throw("The type 'WeirdType' is an unknown field type for field 'validField' of entity 'Valid'.");
      });
    });
    context('when passing an unsupported validation for a field', () => {
      let validator;

      before(() => {
        const entity = new JDLEntity({
          name: 'Valid',
        });
        const field = new JDLField({
          name: 'validField',
          type: FieldTypes.CommonDBTypes.STRING,
        });
        field.addValidation(
          new JDLValidation({
            name: Validations.MIN,
            value: 42,
          })
        );
        entity.addField(field);
        const jdlObject = new JDLObject();
        jdlObject.addEntity(entity);
        validator = createValidator(jdlObject, {
          databaseType: DatabaseTypes.SQL,
        });
      });

      it('should fail', () => {
        expect(() => {
          validator.checkForErrors();
        }).to.throw("The validation 'min' isn't supported for the type 'String'.");
      });
    });
    context('when the source entity of a relationship is missing', () => {
      let validator;

      before(() => {
        const otherEntity = new JDLEntity({
          name: 'Valid',
        });
        const relationship = new JDLRelationship({
          from: 'Source',
          to: otherEntity.name,
          type: RelationshipTypes.ONE_TO_ONE,
          injectedFieldInFrom: 'other',
        });
        const jdlObject = new JDLObject();
        jdlObject.addEntity(otherEntity);
        jdlObject.addRelationship(relationship);
        validator = createValidator(jdlObject, {
          databaseType: DatabaseTypes.SQL,
        });
      });

      it('should fail', () => {
        expect(() => {
          validator.checkForErrors();
        }).to.throw('In the relationship between Source and Valid, Source is not declared.');
      });
    });
    context('when the destination entity of a relationship is missing', () => {
      context('if it is the User entity', () => {
        context('when the skipUserManagement flag is not set', () => {
          let validator;

          before(() => {
            const sourceEntity = new JDLEntity({
              name: 'Source',
            });
            const relationship = new JDLRelationship({
              from: sourceEntity.name,
              to: 'User',
              type: RelationshipTypes.ONE_TO_ONE,
              injectedFieldInFrom: 'other',
            });
            const jdlObject = new JDLObject();
            jdlObject.addEntity(sourceEntity);
            jdlObject.addRelationship(relationship);
            validator = createValidator(jdlObject, {
              databaseType: DatabaseTypes.SQL,
            });
          });

          it('should not fail', () => {
            expect(() => {
              validator.checkForErrors();
            }).not.to.throw();
          });
        });
        context('when skipUserManagement flag is set', () => {
          let checker;

          before(() => {
            const sourceEntity = new JDLEntity({
              name: 'Source',
            });
            const relationship = new JDLRelationship({
              from: sourceEntity.name,
              to: 'User',
              type: RelationshipTypes.ONE_TO_ONE,
              injectedFieldInFrom: 'other',
            });
            const jdlObject = new JDLObject();
            jdlObject.addEntity(sourceEntity);
            jdlObject.addRelationship(relationship);
            checker = createValidator(jdlObject, {
              databaseType: DatabaseTypes.SQL,
              skippedUserManagement: true,
            });
          });

          it('should fail', () => {
            expect(() => {
              checker.checkForErrors();
            }).to.throw('In the relationship between Source and User, User is not declared.');
          });
        });
      });
      context('if it is not the User entity', () => {
        let checker;

        before(() => {
          const sourceEntity = new JDLEntity({
            name: 'Source',
          });
          const relationship = new JDLRelationship({
            from: sourceEntity.name,
            to: 'Other',
            type: RelationshipTypes.ONE_TO_ONE,
            injectedFieldInFrom: 'other',
          });
          const jdlObject = new JDLObject();
          jdlObject.addEntity(sourceEntity);
          jdlObject.addRelationship(relationship);
          checker = createValidator(jdlObject, {
            databaseType: DatabaseTypes.SQL,
          });
        });

        it('should fail', () => {
          expect(() => {
            checker.checkForErrors();
          }).to.throw('In the relationship between Source and Other, Other is not declared.');
        });
      });
    });
    context('when having a JDL with pagination and Cassandra as database type', () => {
      let validator;

      before(() => {
        const jdlObject = new JDLObject();
        jdlObject.addOption(
          new JDLBinaryOption({
            name: BinaryOptions.Options.PAGINATION,
            value: BinaryOptions.Values.pagination.PAGINATION,
          })
        );
        validator = createValidator(jdlObject, { databaseType: DatabaseTypes.CASSANDRA });
      });

      it('should fail', () => {
        expect(() => {
          validator.checkForErrors();
        }).to.throw("Pagination isn't allowed when the application uses Cassandra.");
      });
    });
    context('when having DTOs without services', () => {
      let validator;

      before(() => {
        const jdlObject = new JDLObject();
        jdlObject.addOption(
          new JDLBinaryOption({
            name: BinaryOptions.Options.DTO,
            value: BinaryOptions.Values.dto.MAPSTRUCT,
            entityNames: ['A', 'B', 'C'],
          })
        );
        jdlObject.addOption(
          new JDLBinaryOption({
            name: BinaryOptions.Options.SERVICE,
            value: BinaryOptions.Values.service.SERVICE_CLASS,
            entityNames: ['B'],
          })
        );
        validator = createValidator(jdlObject, { databaseType: DatabaseTypes.SQL });
      });

      it('should not fail', () => {
        expect(() => {
          validator.checkForErrors();
        }).not.to.throw();
      });
    });
    context('when having DTOs with services', () => {
      let validator;

      before(() => {
        const jdlObject = new JDLObject();
        jdlObject.addEntity(
          new JDLEntity({
            name: 'A',
          })
        );
        jdlObject.addEntity(
          new JDLEntity({
            name: 'B',
          })
        );
        jdlObject.addEntity(
          new JDLEntity({
            name: 'C',
          })
        );
        jdlObject.addOption(
          new JDLBinaryOption({
            name: BinaryOptions.Options.DTO,
            value: BinaryOptions.Values.dto.MAPSTRUCT,
            entityNames: ['A', 'B'],
          })
        );
        jdlObject.addOption(
          new JDLBinaryOption({
            name: BinaryOptions.Options.SERVICE,
            value: BinaryOptions.Values.service.SERVICE_CLASS,
            excludedNames: ['C'],
          })
        );
        validator = createValidator(jdlObject, { databaseType: DatabaseTypes.SQL });
      });
      it('should not fail', () => {
        expect(() => {
          validator.checkForErrors();
        }).not.to.throw();
      });
    });
    context('when having a relationship with the User entity as source', () => {
      context('with skipUserManagement', () => {
        let validator;

        before(() => {
          const sourceEntity = new JDLEntity({
            name: 'User',
          });
          const destinationEntity = new JDLEntity({
            name: 'Destination',
          });
          const relationship = new JDLRelationship({
            from: sourceEntity.name,
            to: destinationEntity.name,
            type: RelationshipTypes.ONE_TO_ONE,
            injectedFieldInFrom: 'other',
          });
          const jdlObject = new JDLObject();
          jdlObject.addEntity(sourceEntity);
          jdlObject.addEntity(destinationEntity);
          jdlObject.addRelationship(relationship);
          validator = createValidator(jdlObject, { databaseType: DatabaseTypes.SQL, skippedUserManagement: true });
        });

        it('should not fail', () => {
          expect(() => validator.checkForErrors()).not.to.throw();
        });
      });
      context('without skipUserManagement', () => {
        let validator;

        before(() => {
          const destinationEntity = new JDLEntity({
            name: 'Destination',
          });
          const relationship = new JDLRelationship({
            from: 'User',
            to: destinationEntity.name,
            type: RelationshipTypes.ONE_TO_ONE,
            injectedFieldInFrom: 'other',
          });
          const jdlObject = new JDLObject();
          jdlObject.addEntity(destinationEntity);
          jdlObject.addRelationship(relationship);
          validator = createValidator(jdlObject, { databaseType: DatabaseTypes.SQL, skippedUserManagement: false });
        });

        it('should fail', () => {
          expect(() => validator.checkForErrors()).to.throw(
            /^Relationships from the User entity is not supported in the declaration between 'User' and 'Destination'. You can have this by using the 'skipUserManagement' option.$/
          );
        });
      });
    });
    context('when having a relationship with the User entity as destination', () => {
      context('with skipUserManagement', () => {
        let validator;

        before(() => {
          const sourceEntity = new JDLEntity({
            name: 'Source',
          });
          const destinationEntity = new JDLEntity({
            name: 'User',
          });
          const relationship = new JDLRelationship({
            from: sourceEntity.name,
            to: destinationEntity.name,
            type: RelationshipTypes.ONE_TO_ONE,
            injectedFieldInFrom: 'other',
          });
          const jdlObject = new JDLObject();
          jdlObject.addEntity(sourceEntity);
          jdlObject.addEntity(destinationEntity);
          jdlObject.addRelationship(relationship);
          validator = createValidator(jdlObject, { databaseType: DatabaseTypes.SQL, skippedUserManagement: true });
        });

        it('should not fail', () => {
          expect(() => validator.checkForErrors()).not.to.throw();
        });
      });
      context('without skipUserManagement', () => {
        let validator;

        before(() => {
          const sourceEntity = new JDLEntity({
            name: 'Source',
          });
          const relationship = new JDLRelationship({
            from: sourceEntity.name,
            to: 'User',
            type: RelationshipTypes.ONE_TO_ONE,
            injectedFieldInFrom: 'other',
          });
          const jdlObject = new JDLObject();
          jdlObject.addEntity(sourceEntity);
          jdlObject.addRelationship(relationship);
          validator = createValidator(jdlObject, { databaseType: DatabaseTypes.SQL, skippedUserManagement: false });
        });

        it('should not fail', () => {
          expect(() => validator.checkForErrors()).not.to.throw();
        });
      });
    });
    context('when blueprints is used', () => {
      let parameter;

      before(() => {
        const jdlObject = new JDLObject();
        const logger = {
          warn: callParameter => {
            parameter = callParameter;
          },
        };
        const validator = createValidator(
          jdlObject,
          { blueprints: ['generator-jhipster-nodejs', 'generator-jhipster-dotnetcore'] },
          logger
        );
        validator.checkForErrors();
      });

      it('should warn about not performing jdl validation', () => {
        expect(parameter).to.equal('Blueprints are being used, the JDL validation phase is skipped.');
      });
    });
  });
});


text:
esds-python-tutorial
====================

eSDS python tutorial

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.runtime.resourcemanager;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ConfigurationUtils;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.clusterframework.ContaineredTaskManagerParameters;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.clusterframework.types.ResourceIDRetrievable;
import org.apache.flink.runtime.entrypoint.ClusterInformation;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.metrics.groups.ResourceManagerMetricGroup;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.taskexecutor.TaskManagerServices;

import javax.annotation.Nullable;

/**
 * Resource manager factory which creates active {@link ResourceManager} implementations.
 *
 * <p>The default implementation will call {@link #createActiveResourceManagerConfiguration}
 * to create a new configuration which is configured with active resource manager relevant
 * configuration options.
 *
 * @param <T> type of the {@link ResourceIDRetrievable}
 */
public abstract class ActiveResourceManagerFactory<T extends ResourceIDRetrievable> implements ResourceManagerFactory<T> {

	@Override
	public ResourceManager<T> createResourceManager(
			Configuration configuration,
			ResourceID resourceId,
			RpcService rpcService,
			HighAvailabilityServices highAvailabilityServices,
			HeartbeatServices heartbeatServices,
			FatalErrorHandler fatalErrorHandler,
			ClusterInformation clusterInformation,
			@Nullable String webInterfaceUrl,
			ResourceManagerMetricGroup resourceManagerMetricGroup) throws Exception {
		return createActiveResourceManager(
			createActiveResourceManagerConfiguration(configuration),
			resourceId,
			rpcService,
			highAvailabilityServices,
			heartbeatServices,
			fatalErrorHandler,
			clusterInformation,
			webInterfaceUrl,
			resourceManagerMetricGroup);
	}

	public static Configuration createActiveResourceManagerConfiguration(Configuration originalConfiguration) {
		final int taskManagerMemoryMB = ConfigurationUtils.getTaskManagerHeapMemory(originalConfiguration).getMebiBytes();
		final long cutoffMB = ContaineredTaskManagerParameters.calculateCutoffMB(originalConfiguration, taskManagerMemoryMB);
		final long processMemoryBytes = (taskManagerMemoryMB - cutoffMB) << 20; // megabytes to bytes
		final long managedMemoryBytes = TaskManagerServices.getManagedMemoryFromProcessMemory(originalConfiguration, processMemoryBytes);

		final Configuration resourceManagerConfig = new Configuration(originalConfiguration);
		resourceManagerConfig.setString(TaskManagerOptions.LEGACY_MANAGED_MEMORY_SIZE, managedMemoryBytes + "b");

		return resourceManagerConfig;
	}

	protected abstract ResourceManager<T> createActiveResourceManager(
		Configuration configuration,
		ResourceID resourceId,
		RpcService rpcService,
		HighAvailabilityServices highAvailabilityServices,
		HeartbeatServices heartbeatServices,
		FatalErrorHandler fatalErrorHandler,
		ClusterInformation clusterInformation,
		@Nullable String webInterfaceUrl,
		ResourceManagerMetricGroup resourceManagerMetricGroup) throws Exception;
}


text:
<!DOCTYPE html>

    <title></title>

 Autenticação realizada com sucesso!

Caso a janela não feche automaticamente, clique aqui


text:
<?php

declare(strict_types = 1);

use PHPUnit\Framework\TestCase;
use Sop\JWX\JWA\JWA;
use Sop\JWX\JWE\ContentEncryptionAlgorithm;
use Sop\JWX\JWE\EncryptionAlgorithm\A192GCMAlgorithm;
use Sop\JWX\JWE\EncryptionAlgorithm\AESGCMAlgorithm;

/**
 * @group jwe
 * @group encryption
 *
 * @internal
 */
class A192GCMEncryptionTest extends TestCase
{
    public const PLAINTEXT = 'My hovercraft is full of eels.';
    public const KEY = '0123456789abcdef01234567';
    public const IV = '0123456789ab';
    public const AAD = 'I will not buy this record, it is scratched.';

    public function testCreate()
    {
        $algo = new A192GCMAlgorithm();
        $this->assertInstanceOf(ContentEncryptionAlgorithm::class, $algo);
        return $algo;
    }

    /**
     * @depends testCreate
     *
     * @param ContentEncryptionAlgorithm $algo
     */
    public function testKeySize(AESGCMAlgorithm $algo)
    {
        $this->assertEquals(24, $algo->keySize());
    }

    /**
     * @depends testCreate
     */
    public function testAlgoParamValue(ContentEncryptionAlgorithm $algo)
    {
        $this->assertEquals(JWA::ALGO_A192GCM,
            $algo->encryptionAlgorithmParamValue());
    }

    /**
     * @depends testCreate
     */
    public function testEncrypt(ContentEncryptionAlgorithm $algo)
    {
        [$ciphertext, $auth_tag] = $algo->encrypt(self::PLAINTEXT, self::KEY,
            self::IV, self::AAD);
        $this->assertNotEquals(self::PLAINTEXT, $ciphertext);
        return [$ciphertext, $auth_tag];
    }

    /**
     * @depends testCreate
     * @depends testEncrypt
     */
    public function testDecrypt(ContentEncryptionAlgorithm $algo, array $data)
    {
        $plaintext = $algo->decrypt($data[0], self::KEY, self::IV, self::AAD, $data[1]);
        $this->assertEquals(self::PLAINTEXT, $plaintext);
    }
}


text:
#include "tensorflow/core/lib/io/record_reader.h"

#include <limits.h>

#include "tensorflow/core/lib/core/coding.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/hash/crc32c.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/compression.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/platform/env.h"

namespace tensorflow {
namespace io {

RecordReaderOptions RecordReaderOptions::CreateRecordReaderOptions(
    const string& compression_type) {
  RecordReaderOptions options;
  if (compression_type == "ZLIB") {
    options.compression_type = io::RecordReaderOptions::ZLIB_COMPRESSION;
#if defined(IS_SLIM_BUILD)
    LOG(ERROR) << "Compression is not supported but compression_type is set."
               << " No compression will be used.";
#else
    options.zlib_options = io::ZlibCompressionOptions::DEFAULT();
#endif  // IS_SLIM_BUILD
  } else if (compression_type == compression::kGzip) {
    options.compression_type = io::RecordReaderOptions::ZLIB_COMPRESSION;
#if defined(IS_SLIM_BUILD)
    LOG(ERROR) << "Compression is not supported but compression_type is set."
               << " No compression will be used.";
#else
    options.zlib_options = io::ZlibCompressionOptions::GZIP();
#endif  // IS_SLIM_BUILD
  } else if (compression_type != compression::kNone) {
    LOG(ERROR) << "Unsupported compression_type:" << compression_type
               << ". No compression will be used.";
  }
  return options;
}

RecordReader::RecordReader(RandomAccessFile* file,
                           const RecordReaderOptions& options)
    : options_(options),
      input_stream_(new RandomAccessInputStream(file)),
      last_read_failed_(false) {
  if (options.buffer_size > 0) {
    input_stream_.reset(new BufferedInputStream(input_stream_.release(),
                                                options.buffer_size, true));
  }
  if (options.compression_type == RecordReaderOptions::ZLIB_COMPRESSION) {
// We don't have zlib available on all embedded platforms, so fail.
#if defined(IS_SLIM_BUILD)
    LOG(FATAL) << "Zlib compression is unsupported on mobile platforms.";
#else   // IS_SLIM_BUILD
    input_stream_.reset(new ZlibInputStream(
        input_stream_.release(), options.zlib_options.input_buffer_size,
        options.zlib_options.output_buffer_size, options.zlib_options, true));
#endif  // IS_SLIM_BUILD
  } else if (options.compression_type == RecordReaderOptions::NONE) {
    // Nothing to do.
  } else {
    LOG(FATAL) << "Unrecognized compression type :" << options.compression_type;
  }
}

// Read n+4 bytes from file, verify that checksum of first n bytes is
// stored in the last 4 bytes and store the first n bytes in *result.
//
// offset corresponds to the user-provided value to ReadRecord()
// and is used only in error messages.
Status RecordReader::ReadChecksummed(uint64 offset, size_t n, string* result) {
  if (n >= SIZE_MAX - sizeof(uint32)) {
    return errors::DataLoss("record size too large");
  }

  const size_t expected = n + sizeof(uint32);
  TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(expected, result));

  if (result->size() != expected) {
    if (result->empty()) {
      return errors::OutOfRange("eof");
    } else {
      return errors::DataLoss("truncated record at ", offset);
    }
  }

  const uint32 masked_crc = core::DecodeFixed32(result->data() + n);
  if (crc32c::Unmask(masked_crc) != crc32c::Value(result->data(), n)) {
    return errors::DataLoss("corrupted record at ", offset);
  }
  result->resize(n);
  return Status::OK();
}

Status RecordReader::ReadRecord(uint64* offset, string* record) {
  static const size_t kHeaderSize = sizeof(uint64) + sizeof(uint32);
  static const size_t kFooterSize = sizeof(uint32);

  // Position the input stream.
  int64 curr_pos = input_stream_->Tell();
  int64 desired_pos = static_cast<int64>(*offset);
  if (curr_pos > desired_pos || curr_pos < 0 /* EOF */ ||
      (curr_pos == desired_pos && last_read_failed_)) {
    last_read_failed_ = false;
    TF_RETURN_IF_ERROR(input_stream_->Reset());
    TF_RETURN_IF_ERROR(input_stream_->SkipNBytes(desired_pos));
  } else if (curr_pos < desired_pos) {
    TF_RETURN_IF_ERROR(input_stream_->SkipNBytes(desired_pos - curr_pos));
  }
  DCHECK_EQ(desired_pos, input_stream_->Tell());

  // Read header data.
  Status s = ReadChecksummed(*offset, sizeof(uint64), record);
  if (!s.ok()) {
    last_read_failed_ = true;
    return s;
  }
  const uint64 length = core::DecodeFixed64(record->data());

  // Read data
  s = ReadChecksummed(*offset + kHeaderSize, length, record);
  if (!s.ok()) {
    last_read_failed_ = true;
    if (errors::IsOutOfRange(s)) {
      s = errors::DataLoss("truncated record at ", *offset);
    }
    return s;
  }

  *offset += kHeaderSize + length + kFooterSize;
  DCHECK_EQ(*offset, input_stream_->Tell());
  return Status::OK();
}

SequentialRecordReader::SequentialRecordReader(
    RandomAccessFile* file, const RecordReaderOptions& options)
    : underlying_(file, options), offset_(0) {}

}  // namespace io
}  // namespace tensorflow


text:
This work is licensed under the Creative Commons CC0 License

---

# x2m no longer outputs activities
### xtUML Project Implementation Note

1. Abstract
-----------
There is a regression of functionality in recent versions of x2m.  The
activities are no longer being output to MASL.

2. Document References
----------------------
[1] [9118](https://support.onefact.net/redmine/issues/9118) Headline issue.
3. Background
-------------
x2m is responsible for producing a "smasl" data stream as an xtUML model
is converted to MASL files.  There was a regression where this stopped
working.

4. Requirements
---------------
4.1 The MASL output flow show produce all the required files.

5. Work Required
----------------
5.1 `m2x`
There is a class called "model" in mcshared.  In the work for 9032 we
introduced an attribute "outputcodeblocks" with DefaultValue field set
to true.

Then in x2m where we are handling params we make a call to a "setter"
function that sets the outputcodeblocks attribute to boolean false.  But
if we do not see "-s" then x2m just never calls that setter.  It was
relying on the Default Value of true.  But the generated code did not set
the boolean default to true for the new attriubute when the "model" class
was created.  So it went to C boolean default of false.

Basically x2m always had that attribute "outputcodeblocks" as false whether
we saw -s or not as an argument.

6. Implementation Comments
--------------------------
None.

7. Unit Test
------------
7.1 Use the masl_round_trip script on SAC_OOA to verify exported
  MASL matches the input.

8. Code Changes
---------------
<pre>

Fork: keithbrown/mc  9118_activity_bug

doc/9118_activity_bug_int.md
bin/x2m                                            | Bin 695872 -> 687714 bytes
model/maslout/gen/sys_user_co.c                    |   6 ++++--

</pre>

End
---


text:
import {takeEvery} from 'redux-saga';
import {call, put} from 'redux-saga/effects';
import {REQUEST_GET_SETTINGS} from '../settings.action-types';
import {getSettings} from '../service/settings.service';
import {invalidLogin, retrievedSettings, refreshToken} from '../settings.actions';

function* fetch() {
  try {
    let settings = yield call(getSettings);

    yield put(retrievedSettings(settings));

    yield put(refreshToken());
  } catch (e) {
    console.log(e);

    yield put(invalidLogin());
  }
}

export function* getSettingsSaga() {
  yield* takeEvery(REQUEST_GET_SETTINGS, fetch);
}


text:
// Name:            AcTcUiToolPalette.h
//
// Description:     Header for CAcTcUiToolPalette class. This class
//                  implements the tool palette window and derives from
//                  CAdUiPalette. The tool palette window is embedded in
//                  CAdUiToolPaletteSet window and embeds a tool tray
//                  window CAcUiCatalogView.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef __ACTCUITOOLPALETTE_H__
#define __ACTCUITOOLPALETTE_H__

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "AcTcUi.h"
#include "aduiPalette.h"
#include "AcTcUiPaletteView.h"

class CAcTcUiImpToolPalette;
class AcTcUiSystemInternals;

class ACTCUI_PORT CAcTcUiToolPalette : public CAdUiPalette
{
    friend CAcTcUiImpToolPalette;

    DECLARE_DYNCREATE(CAcTcUiToolPalette);

public:
    CAcTcUiToolPalette();
    virtual ~CAcTcUiToolPalette();

    CAcTcUiPaletteView* GetView             (void);

public:
    // Base class overrides
    virtual BOOL        Create              (CAdUiPaletteSet* pParent);
    BOOL                Create              (DWORD dwStyle,
                                             LPCTSTR pszName,
                                             CAdUiPaletteSet* pParent,
                                             DWORD dwPaletteStyle = 0);
    virtual BOOL        Load                (IUnknown* pUnk);
    virtual bool        CanFrameworkTakeFocus();
    virtual BOOL        Save                (IUnknown* pUnk);
    virtual BOOL        Import              (IUnknown* pUnk, LPCTSTR pszRefPath);
    virtual BOOL        Export              (IUnknown* pUnk, LPCTSTR pszRefPath);
    virtual BOOL        OnKillActive        (void);
    virtual BOOL        GetMinimumSize      (CSize& size);
    virtual void        OnSetActive         (void);
    virtual BOOL        NameEditValidation  (CEdit* pEdit);
    virtual BOOL        Paste               (IDataObject* pDataObject,
                                             int iIndex = -1,
                                             AcTcCatalogItemArray* pNewTools = NULL);
    virtual BOOL        CanPaste            (IDataObject* pDataObject);
    BOOL                SetView             (CAcTcUiPaletteView* pView);

protected:
    //{{AFX_VIRTUAL(CAcTcUiToolPalette)
    //}}AFX_VIRTUAL

protected:
    //{{AFX_MSG(CAcTcUiToolPalette)
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
    afx_msg void OnSetFocus(CWnd* pOldWnd);
    afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
    //}}AFX_MSG
    afx_msg LRESULT OnDragEnter(WPARAM wParam, LPARAM lParam);
    afx_msg LRESULT OnDragOver(WPARAM wParam, LPARAM lParam);
    afx_msg LRESULT OnDragLeave(WPARAM wParam, LPARAM lParam);
    afx_msg LRESULT OnDrop(WPARAM wParam, LPARAM lParam);
    afx_msg LRESULT OnDropEx(WPARAM wParam, LPARAM lParam);
    afx_msg LRESULT OnUpdate(WPARAM wParam, LPARAM lParam);
    afx_msg LRESULT OnEndNameEdit(WPARAM, LPARAM);
    DECLARE_MESSAGE_MAP()

protected:
    void            *   mpImpObj;           // Imp object CAcTcUiImpToolPalette

private:
    friend class AcTcUiSystemInternals;
};

#endif //__ACTCUITOOLPALETTE_H__


text:
package io.janusproject.tests.modules.hazelcast;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteOrder;

import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.Version;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.nio.serialization.StreamSerializer;
import io.janusproject.tests.testutils.AbstractJanusTest;

/**
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
@SuppressWarnings("all")
abstract class AbstractSerializerTest extends AbstractJanusTest {

	protected static <S> void assertWriteRead(S expected, StreamSerializer<S> serializer) throws Exception {
		byte[] content;
		try (OutputStream os = new OutputStream()) {
			serializer.write(os, expected);
			content = os.toByteArray();
		}

		S newObj;
		try (InputStream is = new InputStream(content)) {
			newObj = serializer.read(is);
		}

		assertEquals(expected, newObj);
	}

	/**
	 * @author $Author: sgalland$
	 * @version $FullVersion$
	 * @mavengroupid $GroupId$
	 * @mavenartifactid $ArtifactId$
	 */
	private static class OutputStream extends ByteArrayOutputStream implements ObjectDataOutput {

		public OutputStream() {
			//
		}

		@Override
		public void writeBoolean(boolean v) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeByte(int v) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeShort(int v) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeChar(int v) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeInt(int v) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeLong(long v) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeFloat(float v) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeDouble(double v) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeBytes(String s) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeChars(String s) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeUTF(String s) throws IOException {
			writeObject(s);
		}

		@Override
		public void writeCharArray(char[] chars) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeIntArray(int[] ints) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeLongArray(long[] longs) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeDoubleArray(double[] values) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeFloatArray(float[] values) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeShortArray(short[] values) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeObject(Object object) throws IOException {
			new ObjectOutputStream(this).writeObject(object);
		}

		@Override
		public ByteOrder getByteOrder() {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeByteArray(byte[] arg0) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeData(Data arg0) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeBooleanArray(boolean[] booleans) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void writeUTFArray(String[] values) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public Version getVersion() {
			return Version.UNKNOWN;
		}

		@Override
		public byte[] toByteArray(int padding) {
			byte[] content = toByteArray();
			if (content != null && padding > 0) {
				if (padding > content.length) {
					content = new byte[0];
				} else {
					final int len = content.length - padding;
					byte[] newContent = new byte[len];
					System.arraycopy(content, padding, newContent, 0, Math.min(len, newContent.length));
					content = newContent;
				}
			}
			return content;
		}

	}

	/**
	 * @author $Author: sgalland$
	 * @version $FullVersion$
	 * @mavengroupid $GroupId$
	 * @mavenartifactid $ArtifactId$
	 */
	private static class InputStream extends ByteArrayInputStream implements ObjectDataInput {

		public InputStream(byte[] t) {
			super(t);
		}

		@Override
		public void readFully(byte[] b) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void readFully(byte[] b, int off, int len) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public int skipBytes(int n) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public boolean readBoolean() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public byte readByte() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public int readUnsignedByte() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public short readShort() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public int readUnsignedShort() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public char readChar() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public int readInt() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public long readLong() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public float readFloat() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public double readDouble() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public String readLine() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public String readUTF() throws IOException {
			return (String) readObject();
		}

		@Override
		public char[] readCharArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public int[] readIntArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public long[] readLongArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public double[] readDoubleArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public float[] readFloatArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public short[] readShortArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public <T> T readObject() throws IOException {
			try {
				return (T) new ObjectInputStream(this).readObject();
			} catch (ClassNotFoundException e) {
				throw new IOException(e);
			}
		}

		@Override
		public <T> T readDataAsObject() throws IOException {
			return readObject();
		}

		@Override
		public <T> T readObject(Class type) throws IOException {
			Object instance = readObject();
			if (instance == null || type.isInstance(instance)) {
				return (T) instance;
			}
			throw new IOException();
		}

		@Override
		public ClassLoader getClassLoader() {
			return InputStream.class.getClassLoader();
		}

		@Override
		public ByteOrder getByteOrder() {
			throw new UnsupportedOperationException();
		}

		@Override
		public byte[] readByteArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public Data readData() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public boolean[] readBooleanArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public String[] readUTFArray() throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public Version getVersion() {
			return Version.UNKNOWN;
		}

	}

}


text:
.. _todo-app:

ToDo
#####

.. highlight:: python

Realizacja aplikacji internetowej ToDo (lista zadań do zrobienia) w oparciu o :term:`framework` Flask 0.12.x.
Aplikacja umożliwia dodawanie z określoną datą, przeglądanie i oznaczanie
jako wykonane różnych zadań, które zapisywane będą w bazie danych `SQLite <http://pl.wikipedia.org/wiki/SQLite>`_.

.. contents::
    :depth: 1
    :local:

Początek pracy jest taki sam, jak w przypadku aplikacji :ref:`Quiz <quiz-app>`.
Wykonujemy dwa pierwsze punkty "Projekt i aplikacja" oraz "Strona główna",
tylko katalog aplikacji nazywamy :file:`todo`, a kod zapisujemy w pliku :file:`todo.py`.

Po wykonaniu wszystkich kroków i uruchomieniu serwera testowego powinniśmy w przeglądarce
zobaczyć stronę główną:

.. figure:: img/todo_01.png

Model danych i baza
===================

Jako źródło danych aplikacji wykorzystamy tym razem bazę SQLite3 obsługiwaną za pomocą
Pythonowego modułu `sqlite3 <https://docs.python.org/3.6/library/sqlite3.html>`_.

**Model danych**: w katalogu aplikacji tworzymy plik :file:`schema.sql`,
który zawiera instrukcje języka `SQL <https://pl.wikipedia.org/wiki/SQL>`_
tworzące tabelę z zadaniami i dodające przykładowe dane.

.. raw:: html

plik schema.pl Kod nr

.. highlight:: sql
.. literalinclude:: schema.sql
    :linenos:

W terminalu wydajemy teraz następujące polecenia:

.. raw:: html

Terminal nr

.. code-block:: bash

    ~/todo$ sqlite3 db.sqlite < schema.sql
    ~/todo$ sqlite3 db.sqlite
    sqlite> select * from zadania;
    sqlite> .quit

Pierwsze polecenie tworzy bazę danych w pliku :file:`db.sqlite`.
Drugie otwiera ją w interpreterze. Trzecie to zapytanie SQL, które pobiera
wszystkie dane z tabeli *zadania*. Interpreter zamykamy poleceniem ``.quit``.

.. figure:: img/sqlite.png

Połączenie z bazą
=================

Bazę danych już mamy, teraz pora napisać funkcje umożiwiające łączenie się
z nią z poziomu naszej aplikacji. W pliku :file:`todo.py` dodajemy brakujący kod:

.. raw:: html

Plik todo.py Kod nr

.. highlight:: python
.. literalinclude:: todo_z2.py
    :linenos:
    :lineno-start: 1
    :lines: 1-42

Konfiguracja aplikacji przechowywana jest w obiekcie ``config``, który
jest podklasą słownika i w naszym przypadku zawiera:

* ``SECRET_KEY`` – sekretna wartość wykorzystywana do obsługi sesji;
* ``DATABSE`` – ścieżka do pliku bazy;
* ``SITE_NAME`` – nazwa aplikacji.

Funkcja ``get_db()``:

* ``if not g.get('db'):`` – sprawdzamy, czy obiekt ``g`` aplikacji, służący
  do przechowywania danych kontekstowych, nie zawiera właściwości ``db``,
  czyli połączenia z bazą;
* dalsza część kodu tworzy połączenie w zmiennej ``con`` i zapisuje
  w kontekście (obiekcie ``g``) aplikacji.

Funkcja ``close_db()``:

* ``@app.teardown_appcontext`` – dekorator, który rejestruje funkcję
  zamykającą połączenie z bazą do wykonania po zakończeniu obsługi żądania;
* ``g.db.close()`` – zamknięcie połączenia z bazą.

Lista zadań
===========

Dodajemy widok, czyli funkcję ``zadania()`` powiązaną z adresem URL ``/zadania``:

.. raw:: html

Plik todo.py Kod nr

.. highlight:: python
.. literalinclude:: todo_z3.py
    :linenos:
    :lineno-start: 40
    :lines: 40-45

* ``db = get_db()`` – utworzenie obiektu bazy danych ();
* ``db.execute('select...')`` – wykonanie podanego zapytania SQL,
  czyli pobranie wszystkich zadań z bazy;
* ``fetchall()`` – metoda zwraca pobrane dane w formie listy;

Szablon tworzymy w pliku :file:`todo/templates/zadania_lista.html`:

.. raw:: html

Plik zadania_lista.html. Kod nr

.. highlight:: html
.. literalinclude:: templates/zadania_lista_z3.html
    :linenos:

* ``{% %}`` – tagi używane w szablonach do instrukcji sterujących;
* ``{{ }}`` – tagi używane do wstawiania wartości zmiennych;
* ``{{ config.SITE_NAME }}`` – w szablonie mamy dostęp do obiektu ustawień ``config``;
* ``{% for zadanie in zadania %}`` – pętla odczytująca zadania z listy przekazanej
  do szablonu w zmiennej ``zadania``;

Odnośniki
---------

W szablonie :file:`index.html` warto wstawić link do strony z listą zadań,
czyli kod:

.. raw:: html

Kod nr

.. code-block:: html

Lista zadań

* ``url_for('zadania')`` – funkcja dostępna w szablonach, generuje adres
  powiązany z podaną nazwą funkcji.

**Ćwiczenie**

Wstaw link do strony głównej w szablonie listy zadań.
Po odwiedzeniu strony *127.0.0.1:5000/zadania* powinniśmy zobaczyć listę zadań.

.. figure:: img/todo_03_zadania.png

Dodawanie zadań
===============

Po wpisaniu adresu w przeglądarce i naciśnięciu Enter, wysyłamy do serwera żądanie typu :term:`GET`,
które obsługujemy zwracając klientowi odpowiednie dane (listę zadań).
Dodawanie zadań wymaga przesłania danych z formularza na serwer – są to
żądania typu :term:`POST`, które modyfikują dane aplikacji.

Na początku pliku :file:`todo.py` trzeba, jak zwykle, zaimportować wymagane funkcje:

.. raw:: html

Kod nr

.. highlight:: python
.. literalinclude:: todo_z4.py
    :linenos:
    :lineno-start: 8
    :lines: 8-9

Następnie rozbudujemy widok listy zadań:

.. raw:: html

Kod nr

.. highlight:: python
.. literalinclude:: todo_z4.py
    :linenos:
    :lineno-start: 43
    :lines: 43-63
    :emphasize-lines: 1, 3-16, 21

* ``methods=['GET', 'POST']`` – w liście wymieniamy typy obsługiwanych żądań;
* ``request.form['zadanie']`` – dane przesyłane w żądaniach POST odczytujemy ze
  słownika ``form``;
* ``db.execute(...)`` – wykonujemy zapytanie, które dodaje nowe zadanie,
  w miejsce symboli zastępczych ``(?, ?, ?, ?)`` wstawione zostaną dane
  z listy podanej jako drugi parametr;
* ``flash()`` – funkcja pozwala przygotować komunikaty dla użytkownika,
  które można będzie wstawić w szablonie;
* ``redirect(url_for('zadanie'))`` – przekierowanie użytkownika na adres związany
  z podanym widokiem – żądanie typu GET.

Warto zauważyć, że do szablonu przekazujemy dodatkową zmienną ``error``.

W szablonie :file:`zadania_lista.html` po znaczniku ``
`` umieszczamy kod:

.. raw:: html

Plik zadania_lista.html. Kod nr

.. highlight:: html
.. literalinclude:: templates/zadania_lista_z4.html
    :linenos:
    :lineno-start: 10
    :lines: 10-25

* ``{% if error %}`` – sprawdzamy, czy zmienna ``error`` cokolwiek zawiera;
* ``{% for message in get_flashed_messages() %}`` – pętla odczytująca komunikaty;

.. figure:: img/todo_04_dodawanie.png

Style CSS
=========

O wyglądzie aplikacji decydują arkusze stylów CSS. Umieszczamy je w podkatalogu ``static``
folderu aplikacji. Tworzymy więc plik :file:`~/todo/static/style.css`
z przykładowymi definicjami:

.. raw:: html

Plik style.css. Kod nr

.. highlight:: css
.. literalinclude:: static/style.css
    :linenos:

Arkusz CSS dołączamy do pliku :file:`zadania_lista.html` w sekcji ``head``:

.. raw:: html

Plik zadania_lista.html. Kod nr

.. highlight:: html
.. literalinclude:: templates/zadania_lista_z5.html
    :linenos:
    :lineno-start: 3
    :lines: 3-8
    :emphasize-lines: 4-5

**Ćwiczenie**

Dołącz arkusz stylów CSS również do szablonu :file:`index.html`. Odśwież aplikację w przeglądarce.

.. figure:: img/todo_05_css.png

Zadania wykonane
================

Do każdego zadania dodamy formularz, którego wysłanie będzie oznaczało,
że wykonaliśmy dane zadanie, czyli zmienimy atrybut ``zrobione`` wpisu
z *0* (niewykonane) na *1* (wykonane). Odpowiednie żądanie typu POST
obsłuży nowy widok w pliku :file:`todo.py`, który wstawiamy
przed kodem uruchamiającym aplikację (``if __name__ == '__main__':``):

.. raw:: html

Plik todo.py Kod nr

.. highlight:: python
.. literalinclude:: todo_z6.py
    :linenos:
    :lineno-start: 65
    :lines: 65-73

* ``zadanie_id = request.form['id']`` – odczytujemy przesłany identyfikator zadania;
* ``db.execute('UPDATE zadania SET zrobione=1 WHERE id=?', [zadanie_id])`` – wykonujemy
  zapytanie aktualizujące staus zadania.

W szablonie :file:`zadania_lista.html` modyfikujemy fragment wyświetlający
listę zadań i dodajemy formularz:

.. raw:: html

Plik zadania_lista.html. Kod nr

.. highlight:: html
.. literalinclude:: templates/zadania_lista_z6.html
    :linenos:
    :lineno-start: 29
    :lines: 29-50

Możemy dodawać zadania oraz zmieniać ich status.

.. figure:: img/todo_06_zrobione.png

Zadania dodatkowe
=================

* Dodaj możliwość usuwania zadań.
* Dodaj mechanizm logowania użytkownika tak, aby użytkownik mógł dodawać i edytować tylko swoją listę zadań.

Materiały
=========

**Źródła:**

* :download:`todo.zip <todo.zip>`


text:
import _ from 'lodash'
import moment from 'moment'

import {
  FETCH_WEEK_FAILURE,
  FETCH_WEEK_REQUEST,
  FETCH_WEEK_SUCCESS,
  INVALIDATE_WEEK,
  SELECT_WEEK
} from './week.actions'

import {
  ROUTER_LOCATION_CHANGE
} from '~/src/features/Common/Actions/router.actions'

const ACTION_HANDLERS = {
  [FETCH_WEEK_FAILURE]: (state, action) => {
    const { week } = action
    const specificWeekInfo = state.weekInfo[week]
    const nextSpecificWeekInfo = Object.assign({}, specificWeekInfo, {
      isFetching: false
    })

    const nextWeekInfo = Object.assign({}, state.weekInfo, {
      [week]: nextSpecificWeekInfo
    })

    const nextState = Object.assign({}, state, {
      weekInfo: nextWeekInfo
    })

    return nextState
  },

  [FETCH_WEEK_REQUEST]: (state, action) => {
    // If no specific week info object exists, create it. Likewise with the
    // comics field on the specific week
    const specificWeekInfo = state.weekInfo[action.week]
    const nextSpecificWeekInfo = Object.assign({}, specificWeekInfo, {
      isFetching: true
    })

    const nextWeekInfo = Object.assign({}, state.weekInfo, {
      [action.week]: nextSpecificWeekInfo
    })

    const nextState = Object.assign({}, state, {
      weekInfo: nextWeekInfo
    })
    return nextState
  },

  [FETCH_WEEK_SUCCESS]: (state, action) => {
    const nextComics = state.weekInfo[action.week].isInvalidated
      // We want to remove all existing ids and reset with the new ones if
      // invalidated is flagged
      ? action.comicIds
      // Otherwise, concat them
      : _.uniq(
        state.weekInfo[action.week].comics.slice()
        .concat(action.comicIds))
    const nextWeekInfo = Object.assign({}, state.weekInfo, {
      [action.week]: {
        comics: nextComics,
        isFetching: false,
        isInvalidated: false,
        lastUpdate: moment().unix(),
        total: action.total
      }
    })

    const nextState = Object.assign({}, state, {
      weekInfo: nextWeekInfo
    })
    return nextState
  },

  [INVALIDATE_WEEK]: (state, action) => {
    // Invalidate the specific week
    const specificWeekInfo = state.weekInfo[action.week]
    const nextSpecificWeekInfo = Object.assign({}, specificWeekInfo, {
      isInvalidated: true
    })

    const nextWeekInfo = Object.assign({}, state.weekInfo, {
      [action.week]: nextSpecificWeekInfo
    })

    return Object.assign({}, state, {
      weekInfo: nextWeekInfo
    })
  },

  [ROUTER_LOCATION_CHANGE]: (state, action) => {
    const pathSplit = action.payload.pathname.split('/')
    if (pathSplit.length === 3 && pathSplit[1] === 'week') {
      const nextSelectedWeek = pathSplit[2]
      const nextSpecificWeekInfo = state.weekInfo[nextSelectedWeek] || {
        isFetching: false,
        comics: []
      }

      const nextWeekInfo = Object.assign({}, state.weekInfo, {
        [nextSelectedWeek]: nextSpecificWeekInfo
      })
      return Object.assign({}, state, {
        selectedWeek: nextSelectedWeek,
        weekInfo: nextWeekInfo
      })
    }

    return state
  },

  [SELECT_WEEK]: (state, action) => {
    // If no specific week info object exists, create it. Likewise with the
    // comics field on the specific week
    const specificWeekInfo = state.weekInfo[action.week] || {}
    const nextSpecificWeekInfo = Object.assign({}, specificWeekInfo, {
      isFetching: false,
      comics: specificWeekInfo.comics || []
    })

    const nextWeekInfo = Object.assign({}, state.weekInfo, {
      [action.week]: nextSpecificWeekInfo
    })

    const nextState = Object.assign({}, state, {
      selectedWeek: action.week,
      weekInfo: nextWeekInfo
    })

    return nextState
  }
}

const initialState = {
  selectedWeek: '2015-01-01',
  weekInfo: {
    '2015-01-01': {
      isFetching: true,
      comics: []
    }
  }
}

export default function weekReducer(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]
  return handler ? handler(state, action) : state
}


text:
#!/bin/bash

# This script tries to apply  all patches from ${PATCHES_DIR} directory
# on the specified (${PKG_VER_FOR_VERIFICATION}) version of packages
# (Installed or Candidate)
#
# Return:
#     0 - ok
#     x - error
# Output:
#     Result of verification

APT_CONF=${1:-$APT_CONF}
APT_CONF=${APT_CONF:-"/root/mos_mu/apt/apt.conf"}
PATCHES_DIR=${2:-$PATCHES_DIR}
PATCHES_DIR=${PATCHES_DIR:?"PATCHES_DIR is undefined!"}
VERIFICATION_DIR=${3:-$VERIFICATION_DIR}
VERIFICATION_DIR=${VERIFICATION_DIR:?"VERIFICATION_DIR is undefined!"}
PKG_VER_FOR_VERIFICATION=${4:-$PKG_VER_FOR_VERIFICATION}
PKG_VER_FOR_VERIFICATION=${PKG_VER_FOR_VERIFICATION:?"PKG_VER_FOR_VERIFICATION is undefined!"}
IGNORE_APPLIED_PATCHES=${5:-$IGNORE_APPLIED_PATCHES}
IGNORE_APPLIED_PATCHES=${IGNORE_APPLIED_PATCHES:-"False"}
APT_UPGRADE=${6:-$APT_UPGRADE}

CACHED_PKG_FILES="/var/cache/apt/archives/"

# Gets patackage name from patch
#
# Return:
#     0 - ok
#     x - error
# Global vars:
#   OUT - Error or Warning messages
#   PKG - Package name
get_pkg_name_from_patch()
{
    OUT=""
    PKG=""
    local RET=0
    local PATCH=${1:?"Please specify patch's filename"}

    # Get list of customized files from patch file
    local FILES=$(awk '/\+\+\+ \// {print $2}' "${PATCH}")
    # Make sure that all customized files are belonged to the same Package
    for FILE in ${FILES}; do
        [ -f "${FILE}" ] || {
            OUT+="[WARN]   ${FILE} skipped since it is absent\n";
            continue; }
        PACK=$(dpkg -S "${FILE}")
        PACK=$(echo -e "${PACK}" | awk '{print $1}')
	# Make sure that this file isn't belonged to the several packages
        [[ "${PACK}" =~ .*diversion*. ]] && {
            (( RET |= 1 ));
            OUT+="[ERROR]  File ${FILE} is diversion\n";
            continue; }
        PACK=${PACK/\:/}
        [ -z "${PKG}" ] && {
            PKG="${PACK}";
            continue; }
        [[ "${PACK}" != "${PKG}" ]] && {
            (( RET |= 1 ));
            OUT+="[ERROR]  Affect more than one package: ${PKG} != ${PACK} (${FILE})\n";
	    continue; }
    done
    return "${RET}"
}

# Returns a path to the deb file of specified package and version
#
# Return:
#     0 - ok
#     x - error # Global Vars:
# Global Vars:
# PKG_FILE - deb file for required package and version
function get_deb ()
{
    local PKG=${1:?"Please specify package name."}
    local VERS=${2:?"Please specify package version"}
    PKG_FILE=$(find "${CACHED_PKG_FILES}" -type f -name "${PKG}*${VERS##*:}*.deb")
    [ -f "${PKG_FILE}" ] && return 0

    apt-get -c "${APT_CONF}" download "${PKG}=${VERS}" &> /dev/null || return -1
    PKG_FILE=$(find . -type f -name "${PKG}*${VERS##*:}*.deb")
    [ -f "${PKG_FILE}" ] && return 0

    return 1
}

# Unpacks specified deb file
#
# Return:
#     0 - ok
#     x - error
function unpack_deb ()
{
    local PKG_FILE=${1:?"Please specify package name."}
    [ -f "${PKG_FILE}" ] || return -1
    local DATA=$(ar t "${PKG_FILE}" | grep data.tar)
    local ARCH_KEY=''
    case $(echo "${DATA}" | awk -F '.' '{print $3}') in
	'gz')
	    ARCH_KEY='z'
	    ;;
	'xz')
	    ARCH_KEY='J'
            ;;
	*)
	    return -2
	    ;;
    esac
    ar p "${PKG_FILE}" "${DATA}" | tar x"${ARCH_KEY}" || return -3
}

cd "${PATCHES_DIR}" &>/dev/null || exit 0

HOLD_PKGS=$(apt-mark showhold)

RET=0
# Check patches
PATCHES=$(find . -type f -name "*.patch" |sort)
for PATCH in ${PATCHES}; do
    cd "${PATCHES_DIR}" || exit -1
    echo -e "\n-------- ${PATCH}"
    get_pkg_name_from_patch "${PATCH}"
    RS=$?
    [ -n "${OUT}" ] &&
        echo -e "${OUT}"
    (( RS != 0 ))  && {
        (( RET |= 1 ));
        continue; }
    # Whether package is installed on this node ?
    [ -z "${PKG}" ] &&
        continue
    # Whether this package should be keeped ?
    echo "${HOLD_PKGS}" | grep ${PKG} &>/dev/null  && {
        echo "[SKIP]   ${PKG} is on hold";
        continue; }

    # Identify required version
    EXTRACTED_PKG=${VERIFICATION_DIR}/${PKG}
    POLICY=$(apt-cache -c "${APT_CONF}" policy "${PKG}" 2>/dev/null ) || exit -1
    VERS=$(echo -e "${POLICY}" | grep "${PKG_VER_FOR_VERIFICATION}" | awk '{print $2}')

    [ -d "${EXTRACTED_PKG}/${VERS}" ] ||
        mkdir -p "${EXTRACTED_PKG}/${VERS}"
    cd "${EXTRACTED_PKG}/${VERS}" &&
        rm -rf ./*

    get_deb "${PKG}" "${VERS}"

    unpack_deb "${PKG_FILE}" || exit -1

    # Verify patch applying
    cd "${EXTRACTED_PKG}" || exit -1

    cp -f "${PATCHES_DIR}/${PATCH}" .
    PATCH_FILENAME=${PATCH##*/}
    PATCH_OUT=$(patch -p1 -Nu -r- -d "${VERS}" < "${PATCH_FILENAME}")
    RES=$?
    echo -e "${PATCH_OUT}"
    if (( RES != 0 )); then
        if [ "${IGNORE_APPLIED_PATCHES,,}" != "true" ]; then
            PATCH_RES=$(grep -E "Skipping|ignored" <<< "${PATCH_OUT}")
            if [ -n "${PATCH_RES}" ]; then
                echo "[ERROR]  Failed to apply ${PATCH}"
                (( RET |= 4))
                continue
            fi
        fi
        # FIXME: Need to be tested and modified !?
        # Only the following lines should present in output:
        #    patching file usr/lib/python2.7/dist-packages/......
        #    Reversed (or previously applied) patch detected!  Skipping patch.
        #    2 out of 2 hunks ignored
        PATCH_RES=$(grep -Ev "patching|Skipping|ignored" <<< "${PATCH_OUT}")
        if [ -n "${PATCH_RES}" ]; then
            echo "[ERROR]  Failed to apply ${PATCH}"
            (( RET |= 8))
            continue
        fi
    fi
    echo "[OK]     ${PKG} is customized successfully"
done

if (( (RET & 4) == 4 )); then
    echo ""
    echo "Some patches look as already applied."
    echo "Please make sure that these patches were included in MU"
    echo "If you sure that it is, you can use the following flag:"
    echo ' {"ignore_applied_patches":true}'
    echo "for ignoring these patches."
fi
if (( (RET & 8) == 8 )); then
    echo ""
    echo "Some patches failed to apply."
    echo "Please resolve this issue:"
    echo " 1. Go on the failed nodes in 'verification' folder"
    echo " 2. Handle the issue with patch applying."
    echo " 3. Copy this patch  to 'patches' folder"
    echo ' 4. use -e {"use_current_customizations":false} for skipping'
    echo "    verification and using of gathered customizations."
fi

exit "${RET}"


text:
package org.eclipse.gemini.blueprint.internal.service.collection;

import org.eclipse.gemini.blueprint.service.importer.support.internal.collection.DynamicSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * @author Costin Leau
 */
public class DynamicSetTest {
    private Set dynamicSet;

    private Object obj;

    private List list;

    @Before
    public void setUp() throws Exception {
        dynamicSet = new DynamicSet();
        obj = new Object();
        list = new ArrayList();
        list.add(obj);
        list.add(obj);

    }

    @After
    public void tearDown() throws Exception {
        dynamicSet = null;
        list = null;
        obj = null;
    }

    @Test
    public void testNoDuplicatesWhileAdding() {
        Object obj = new Object();
        assertTrue(dynamicSet.add(obj));
        assertFalse(dynamicSet.add(obj));
    }

    @Test
    public void testNoDuplicatesAfterRemovalAndAdding() {
        Object obj = new Object();
        assertTrue(dynamicSet.add(obj));
        assertTrue(dynamicSet.remove(obj));
        assertTrue(dynamicSet.add(obj));
    }

    @Test
    public void testNullAllowed() {
        assertTrue(dynamicSet.add(null));
        assertFalse(dynamicSet.add(null));
    }

    @Test
    public void testAddAllWithCollectionThatContainsDuplicates() {
        dynamicSet.addAll(list);
        assertTrue(dynamicSet.contains(obj));
        assertFalse(dynamicSet.add(obj));
    }

    @Test
    public void testContainsAllWithCollectionsThatContainsDuplicates() {
        assertFalse(dynamicSet.containsAll(list));
        dynamicSet.add(obj);
        assertTrue(dynamicSet.containsAll(list));
    }

    @Test
    public void testRetainAllWithCollectionThatContainsDuplicates() {
        assertFalse(dynamicSet.retainAll(list));
        dynamicSet.add(obj);
        assertFalse(dynamicSet.retainAll(list));
        dynamicSet.add(new Object());
        assertTrue(dynamicSet.retainAll(list));
    }

    @Test
    public void testRemoveAllWithCollectionThatContainsDuplicates() {
        assertFalse(dynamicSet.removeAll(list));
        dynamicSet.add(obj);
        assertTrue(dynamicSet.removeAll(list));
        assertTrue(dynamicSet.isEmpty());
    }

}


text:
<?php

namespace aotd\PSR3LogAdapter;

use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use yii\base\component;
use yii\log\Logger as YiiLogger;

/**
 * Class Logger
 * @package aotd\PSR3LogAdapter
 */
class Logger extends Component implements LoggerInterface
{
    use LoggerTrait;

    /**
     * @var string Yii category for the logged messages.
     */

    public $defaultCategory = 'PSR-3-log';

    public $logLevelMap = [
        'emergency' => YiiLogger::LEVEL_ERROR,
        'alert'     => YiiLogger::LEVEL_ERROR,
        'critical'  => YiiLogger::LEVEL_ERROR,
        'error'     => YiiLogger::LEVEL_ERROR,
        'warning'   => YiiLogger::LEVEL_WARNING,
        'notice'    => YiiLogger::LEVEL_INFO,
        'info'      => YiiLogger::LEVEL_INFO,
        'debug'     => YiiLogger::LEVEL_TRACE,
    ];

    /**
     * Log a message, transforming from PSR3 log levels to the closest Yii2
     * equivalent.
     *
     * @param mixed $level
     * @param string $message
     * @param array $context
     */
    public function log($level, $message, array $context = [])
    {
        /** @var \yii\log\Logger $logger */
        $logger = \Yii::getLogger();

        $category = isset($context['category']) ? $context['category'] : $this->defaultCategory;

        $message = $this->interpolate($message, $context);

        $logger->log($message, $this->logLevelMap[$level], $category);
    }

    private function interpolate($message, array $context = [])
    {
        $replace = [];
        foreach ($context as $key => $val) {
            if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
                $replace['{' . $key . '}'] = $val;
            }
        }

        return strtr($message, $replace);
    }
}


text:
(function (angular) {
    'use strict';

    angular
        .module('cogeoApp')
        .factory('accessLog', accessLog);

    accessLog.$inject = [
        'CONFIG',
        'httpRequest',
        '$q',
        'deviceDetector',
        '$filter',
        'cozenEnhancedLogs',
        'cozenLanguage'
    ];

    function accessLog(CONFIG, httpRequest, $q, deviceDetector, $filter, cozenEnhancedLogs, cozenLanguage) {
        return {
            getAccessLog: getAccessLog
        };

        // Return a deferred with fresh access log object
        // Always a resolve deferred (may content less or more data)
        // Note: ipinfo return this: {country, hostname, ip, loc, org, postal, region}
        function getAccessLog() {
            var accessLog = {
                appLanguage   : cozenLanguage.getCurrentLanguage(),
                appVersion    : CONFIG.internal.appVersion,
                browserName   : $filter('cozenCapitalize')(deviceDetector.browser, true, true),
                browserVersion: $filter('cozenCapitalize')(deviceDetector.browser_version, true, true),
                osName        : $filter('cozenCapitalize')(deviceDetector.os, true, true),
                osVersion     : $filter('cozenCapitalize')(deviceDetector.os_version, true, true)
            };
            var deferred  = $q.defer();
            httpRequest.customRequest('GET', 'http://ipinfo.io')
                .then(function (response) {
                    accessLog = angular.merge({}, response.data, accessLog);
                    sendLog(accessLog);
                    deferred.resolve(accessLog);
                })
                .catch(function (response) {
                    accessLog = angular.merge({}, {
                        ip      : null,
                        hostname: null,
                        city    : null,
                        region  : null,
                        country : null,
                        loc     : null,
                        org     : null,
                        postal  : null
                    }, accessLog);
                    sendLog(accessLog);
                    deferred.resolve(accessLog);
                })
            ;
            return deferred.promise;

            // Just a log
            function sendLog(accessLog) {
                cozenEnhancedLogs.info.explodeObject('accessLog', 'getAccessLog digging result', accessLog);
            }
        }
    }

})(window.angular);


text:
namespace Ui {
class PClassical;
}

class PClassical : public QDialog
{
    Q_OBJECT

public:
    explicit PClassical(QWidget *parent = 0);
    ~PClassical();

public slots:
    void seData(QString str);

private slots:

    void on_pushButton_2_clicked();

    void on_pushButton_3_clicked();

    void on_pushButton_4_clicked();

    void on_checkBox_14_clicked();

    void on_checkBox_15_clicked();

    void on_spinBox_valueChanged();

    void showPointToolTip(QMouseEvent *event);

private:
    Ui::PClassical *ui;
};

#endif // PCLASSICAL_H


text:
/*
 * Revision Control Information
 *
 * $Id: pipefork.c,v 1.6 2004/08/18 00:06:42 fabio Exp fabio $
 *
 */
/* LINTLIBRARY */

#include "util.h"
#include <sys/wait.h>

/*
 * util_pipefork - fork a command and set up pipes to and from
 *
 * Rick L Spickelmier, 3/23/86
 * Richard Rudell, 4/6/86
 * Rick L Spickelmier, 4/30/90, got rid of slimey vfork semantics
 *
 * Returns:
 *   1 for success, with toCommand and fromCommand pointing to the streams
 *   0 for failure
 */

/* ARGSUSED */
int
util_pipefork(
  char * const *argv,		/* normal argv argument list */
  FILE **toCommand,	/* pointer to the sending stream */
  FILE **fromCommand,	/* pointer to the reading stream */
  int *pid)
{
#ifdef UNIX
    int forkpid, waitPid;
    int topipe[2], frompipe[2];
    char buffer[1024];
    int status;

    /* create the PIPES...
     * fildes[0] for reading from command
     * fildes[1] for writing to command
     */
    (void) pipe(topipe);
    (void) pipe(frompipe);

#ifdef __CYGWIN32__
    if ((forkpid = fork()) == 0) {
#else
    if ((forkpid = vfork()) == 0) {
#endif
	/* child here, connect the pipes */
	(void) dup2(topipe[0], fileno(stdin));
	(void) dup2(frompipe[1], fileno(stdout));

	(void) close(topipe[0]);
	(void) close(topipe[1]);
	(void) close(frompipe[0]);
	(void) close(frompipe[1]);

	(void) execvp(argv[0], argv);
	(void) sprintf(buffer, "util_pipefork: can not exec %s", argv[0]);
	perror(buffer);
	(void) _exit(1);
    }

    if (pid) {
        *pid = forkpid;
    }

#ifdef __CYGWIN32__
    waitPid = waitpid(-1, &status, WNOHANG);
#else
    waitPid = wait3(&status, WNOHANG, NULL);
#endif

    /* parent here, use slimey vfork() semantics to get return status */
    if (waitPid == forkpid && WIFEXITED(status)) {
	return 0;
    }
    if ((*toCommand = fdopen(topipe[1], "w")) == NULL) {
	return 0;
    }
    if ((*fromCommand = fdopen(frompipe[0], "r")) == NULL) {
	return 0;
    }
    (void) close(topipe[0]);
    (void) close(frompipe[1]);
    return 1;
#else
    (void) fprintf(stderr,
	"util_pipefork: not implemented on your operating system\n");
    return 0;
#endif
}


text:
<?php
/**
 * This file is part of the Ray.WebFormModule package.
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
namespace Ray\WebFormModule\Exception;

class InvalidOnFailureMethod extends \LogicException
{
}


text:
from rdflib import Graph, Literal, BNode, Namespace, RDF, XSD
import queries
from dateutil import parser

global SSN
global GEO
global DUL

# SSN Namespace
SSN = Namespace('https://www.w3.org/2005/Incubator/ssn/ssnx/ssn#')

# Geo Namespace
GEO = Namespace('http://www.w3.org/2003/01/geo/wgs84_pos#')

# DUL Namespace
DUL = Namespace('http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#')

def addToGraph(event, graph):
    graph.bind('ssn', SSN)
    graph.bind('geo', GEO)
    graph.bind('dul', DUL)
    observation = BNode();

    oTime = BNode();
    # Observation
    graph.add((observation, RDF.type, SSN.Observation))
    graph.add((oTime, RDF.type, DUL.TimeInterval))
    graph.add((observation, SSN.observationSamplingTime, oTime))

    # Time
    date = parser.parse(event['pickup_datetime'])
    t = Literal(date.strftime("%Y-%m-%dT%H:%M:%S"), datatype=XSD.dateTime)
    #t = Literal(event['dropoff_datetime'])
    #print(event['dropoff_datetime'])
    graph.add((oTime, DUL.hasRegionDataValue, t))

    # SensorOutput
    sensorOutput = BNode();

    graph.add((sensorOutput, RDF.type, SSN.SensorOutput))
    graph.add((observation, SSN.observationResult, sensorOutput))

    # ObservationValue
    observationValue = BNode()
    startLocation = BNode()
    endLocation = BNode()
    graph.add((observationValue, RDF.type, SSN.ObservationValue))
    graph.add((sensorOutput, SSN.hasValue, observationValue))

    # Start and End Location
    graph.add((observationValue, SSN.hasStartLocation, startLocation))
    graph.add((observationValue, SSN.hasEndLocation, endLocation))
    graph.add((startLocation, RDF.type, GEO.location))
    graph.add((endLocation, RDF.type, GEO.location))

    # Start Location
    lat = Literal(event['pickup_latitude'], datatype=XSD.float)
    long = Literal(event['pickup_longitude'], datatype=XSD.float)

    # Adding the start location
    graph.add((startLocation, GEO.lat, lat))
    graph.add((startLocation, GEO.long, long))

    # End Location
    lat = Literal(event['dropoff_latitude'], datatype=XSD.float)
    long = Literal(event['dropoff_longitude'], datatype=XSD.float)

    # Adding the start location
    graph.add((endLocation, GEO.lat, lat))
    graph.add((endLocation, GEO.long, long))

    #Duration
    date1 = parser.parse(event['dropoff_datetime'])
    date2 = parser.parse(event['pickup_datetime'])
    dur = date1 - date2
    duration = Literal(str(dur), datatype=XSD.float)

    graph.add((observation, SSN.hasDuration, duration))
    return graph

def removeFromGraph(timestamp, graph):
    results = graph.query(queries.getEvents(timestamp))

    print len(results)
    for result in results:
        for node in result:
            graph.remove((node, None, None))


text:
package com.ocean.rpc.util;

public class a {

	public static void main(String args[]){
		byte[] a={'\n','4'};
		System.out.println(a+"b");
	}
}


text:
<?php

namespace Drupal\Tests\node\Functional\Views\Wizard;

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\views\Functional\Wizard\WizardTestBase;

/**
 * Tests node wizard and content type with hidden Taxonomy Term Reference field.
 *
 * @group Views
 * @group node
 */
class HiddenTaxonomyTermReferenceFieldWizardTest extends WizardTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * Modules to enable.
   *
   * @var array
   */
  protected static $modules = ['taxonomy'];

  /**
   * Tests content type with a hidden Taxonomy Term Reference field.
   */
  public function testHiddenTaxonomyTermReferenceField() {
    // Create Article node type.
    $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);

    // Create a taxonomy_term_reference field on the article Content Type. By
    // not assigning a widget to that field we make sure it is hidden on the
    // Form Display.
    $field_name = mb_strtolower($this->randomMachineName());
    FieldStorageConfig::create([
      'field_name' => $field_name,
      'entity_type' => 'node',
      'type' => 'entity_reference',
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
      'settings' => [
        'target_type' => 'taxonomy_term',
      ],
    ])->save();
    FieldConfig::create([
      'field_name' => $field_name,
      'bundle' => 'article',
      'entity_type' => 'node',
      'settings' => [
        'handler' => 'default',
      ],
    ])->save();

    $this->drupalGet('admin/structure/views/add');
    $this->assertSession()->statusCodeEquals(200);
  }

}


text:
package org.elasticsearch.xpack.core.ml.job.config;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.xcontent.ConstructingObjectParser;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.ToXContentObject;
import org.elasticsearch.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.Objects;

public class ModelPlotConfig implements ToXContentObject, Writeable {

    public static final ParseField TYPE_FIELD = new ParseField("model_plot_config");
    public static final ParseField ENABLED_FIELD = new ParseField("enabled");
    public static final ParseField TERMS_FIELD = new ParseField("terms");
    public static final ParseField ANNOTATIONS_ENABLED_FIELD = new ParseField("annotations_enabled");

    // These parsers follow the pattern that metadata is parsed leniently (to allow for enhancements), whilst config is parsed strictly
    public static final ConstructingObjectParser<ModelPlotConfig, Void> LENIENT_PARSER = createParser(true);
    public static final ConstructingObjectParser<ModelPlotConfig, Void> STRICT_PARSER = createParser(false);

    private static ConstructingObjectParser<ModelPlotConfig, Void> createParser(boolean ignoreUnknownFields) {
        ConstructingObjectParser<ModelPlotConfig, Void> parser = new ConstructingObjectParser<>(
            TYPE_FIELD.getPreferredName(),
            ignoreUnknownFields,
            a -> new ModelPlotConfig((boolean) a[0], (String) a[1], (Boolean) a[2])
        );

        parser.declareBoolean(ConstructingObjectParser.constructorArg(), ENABLED_FIELD);
        parser.declareString(ConstructingObjectParser.optionalConstructorArg(), TERMS_FIELD);
        parser.declareBoolean(ConstructingObjectParser.optionalConstructorArg(), ANNOTATIONS_ENABLED_FIELD);

        return parser;
    }

    private final boolean enabled;
    private final String terms;
    private final boolean annotationsEnabled;

    public ModelPlotConfig() {
        this(true, null, null);
    }

    public ModelPlotConfig(boolean enabled, String terms, Boolean annotationsEnabled) {
        this.enabled = enabled;
        this.terms = terms;
        this.annotationsEnabled = annotationsEnabled != null ? annotationsEnabled : enabled;
    }

    public ModelPlotConfig(StreamInput in) throws IOException {
        enabled = in.readBoolean();
        terms = in.readOptionalString();
        annotationsEnabled = in.readBoolean();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeBoolean(enabled);
        out.writeOptionalString(terms);
        out.writeBoolean(annotationsEnabled);
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.field(ENABLED_FIELD.getPreferredName(), enabled);
        if (terms != null) {
            builder.field(TERMS_FIELD.getPreferredName(), terms);
        }
        builder.field(ANNOTATIONS_ENABLED_FIELD.getPreferredName(), annotationsEnabled);
        builder.endObject();
        return builder;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public String getTerms() {
        return terms;
    }

    public boolean annotationsEnabled() {
        return annotationsEnabled;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }

        if (other instanceof ModelPlotConfig == false) {
            return false;
        }

        ModelPlotConfig that = (ModelPlotConfig) other;
        return this.enabled == that.enabled && Objects.equals(this.terms, that.terms) && this.annotationsEnabled == that.annotationsEnabled;
    }

    @Override
    public int hashCode() {
        return Objects.hash(enabled, terms, annotationsEnabled);
    }
}


text:
package cf;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Names identify ourselves.
 *
 * @author debmalyajash
 *
 */
public class Names {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Names self = new Names();
		String[] names = new String[] { "Raymond", "Nora", "Daniel", "Louie", "Peter", "Esteban" };
		System.out.println(Arrays.toString(self.chainNames(names)));

	}

	/**
	 * You're given an array of names, where each name is given as a string.
	 * Your task is to link these names into a chain, so that the ith name
	 * starts with the same letter the (i - th)th name ends, and return this
	 * chain as a list.
	 *
	 * All names should be used. It is guaranteed that each name starts with a
	 * unique letter. It is also guaranteed that there is only one solution.
	 *
	 *
	 * Example
	 *
	 * For
	 *
	 * names = ["Raymond", "Nora", "Daniel", "Louie", "Peter", "Esteban"] the
	 * output should be
	 *
	 * chainNames(names) = ["Peter", "Raymond", "Daniel", "Louie", "Esteban",
	 * "Nora"]
	 *
	 * @param names
	 * @return
	 */
	String[] chainNames(String[] names) {

		// Find the first name to put in the chain.
		// Whose first letter of name is not end letter of anybody's name.
		Map<Character, String> f = new HashMap<>();
		Map<Character, String> l = new HashMap<>();
		List<String> nl = new ArrayList<>();

		for (String e : names) {
			f.put(Character.toLowerCase(e.charAt(0)), e);
			l.put(e.charAt(e.length() - 1), e);
		}

		String a = "";
		 Iterator<Character> i = f.keySet().iterator();
		while (i.hasNext()) {
			Character n = i.next();
			String p = l.get(n);
			if (p == null) {
				// this will be the first name.
				a = f.get(n);
				nl.add(a);
				String b = f.get(a.charAt(a.length() - 1));
				while (b != null) {
					nl.add(b);
					a = b;
					b = f.get(a.charAt(a.length() - 1));
					if (nl.size() == names.length){
						break;
					}
				}

				break;
			}
		}

		return nl.toArray(new String[0]);

	}

	String[] chainNames0(String[] names) {

		// Find the first name to put in the chain.
		// Whose first letter of name is not end letter of anybody's name.
		Map<Character, String> f = new HashMap<>();
		Map<Character, String> l = new HashMap<>();
		List<String> nl = new ArrayList<>();

		for (String e : names) {
			f.put(Character.toLowerCase(e.charAt(0)), e);
			l.put(e.charAt(e.length() - 1), e);
		}

		String a = "";
		Iterator<Entry<Character, String>> i = f.entrySet().iterator();
		while (i.hasNext()) {
			Entry<Character, String> n = i.next();
			String p = l.get(n.getKey());
			if (p == null) {
				// this will be the first name.
				a = n.getValue();
				nl.add(a);
				String b = f.get(a.charAt(a.length() - 1));
				while (b != null) {
					nl.add(b);
					a = b;
					b = f.get(a.charAt(a.length() - 1));
				}

				break;
			}
		}

		return nl.toArray(new String[0]);

	}

}


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

/**
 *
 * @author tux
 * @param <T>
 */
public interface Enumable<T> {

    public T getValue();

    public Integer compareTo(Enumable e);
}


text:
/** \file
 * Content for image/bmp (implementation)
 */

#include <assert.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <libnsbmp.h>

#include "utils/config.h"
#include "content/content_protected.h"
#include "content/hlcache.h"
#include "desktop/plotters.h"
#include "utils/log.h"
#include "utils/messages.h"
#include "utils/utils.h"

#include "image/bitmap.h"
#include "image/bmp.h"

typedef struct nsbmp_content {
	struct content base;

	bmp_image *bmp;	/** BMP image data */

	struct bitmap *bitmap;	/**< Created NetSurf bitmap */
} nsbmp_content;

static nserror nsbmp_create_bmp_data(nsbmp_content *bmp)
{
	union content_msg_data msg_data;

	bmp->bmp = calloc(sizeof(struct bmp_image), 1);
	if (bmp->bmp == NULL) {
		msg_data.error = messages_get("NoMemory");
		content_broadcast(&bmp->base, CONTENT_MSG_ERROR, msg_data);
		return NSERROR_NOMEM;
	}

	bmp_create(bmp->bmp, &bmp_bitmap_callbacks);

	return NSERROR_OK;
}

static nserror nsbmp_create(const content_handler *handler,
		lwc_string *imime_type, const struct http_parameter *params,
		llcache_handle *llcache, const char *fallback_charset,
		bool quirks, struct content **c)
{
	nsbmp_content *bmp;
	nserror error;

	bmp = calloc(1, sizeof(nsbmp_content));
	if (bmp == NULL)
		return NSERROR_NOMEM;

	error = content__init(&bmp->base, handler, imime_type, params,
			llcache, fallback_charset, quirks);
	if (error != NSERROR_OK) {
		free(bmp);
		return error;
	}

	error = nsbmp_create_bmp_data(bmp);
	if (error != NSERROR_OK) {
		free(bmp);
		return error;
	}

	*c = (struct content *) bmp;

	return NSERROR_OK;
}

/**
 * Callback for libnsbmp; forwards the call to bitmap_create()
 *
 * \param  width   width of image in pixels
 * \param  height  width of image in pixels
 * \param  state   a flag word indicating the initial state
 * \return an opaque struct bitmap, or NULL on memory exhaustion
 */
static void *nsbmp_bitmap_create(int width, int height, unsigned int bmp_state)
{
	unsigned int bitmap_state = BITMAP_NEW;

	/* set bitmap state based on bmp state */
	bitmap_state |= (bmp_state & BMP_OPAQUE) ? BITMAP_OPAQUE : 0;
	bitmap_state |= (bmp_state & BMP_CLEAR_MEMORY) ?
			BITMAP_CLEAR_MEMORY : 0;

	/* return the created bitmap */
	return bitmap_create(width, height, bitmap_state);
}

/* The Bitmap callbacks function table;
 * necessary for interaction with nsbmplib.
 */
bmp_bitmap_callback_vt bmp_bitmap_callbacks = {
	.bitmap_create = nsbmp_bitmap_create,
	.bitmap_destroy = bitmap_destroy,
	.bitmap_get_buffer = bitmap_get_buffer,
	.bitmap_get_bpp = bitmap_get_bpp
};

static bool nsbmp_convert(struct content *c)
{
	nsbmp_content *bmp = (nsbmp_content *) c;
	bmp_result res;
	union content_msg_data msg_data;
	uint32_t swidth;
	const char *data;
	unsigned long size;
	char *title;

	/* set the bmp data */
	data = content__get_source_data(c, &size);

	/* analyse the BMP */
	res = bmp_analyse(bmp->bmp, size, (unsigned char *) data);
	switch (res) {
		case BMP_OK:
			break;
		case BMP_INSUFFICIENT_MEMORY:
			msg_data.error = messages_get("NoMemory");
			content_broadcast(c, CONTENT_MSG_ERROR, msg_data);
			return false;
		case BMP_INSUFFICIENT_DATA:
		case BMP_DATA_ERROR:
			msg_data.error = messages_get("BadBMP");
			content_broadcast(c, CONTENT_MSG_ERROR, msg_data);
			return false;
	}

	/* Store our content width and description */
	c->width = bmp->bmp->width;
	c->height = bmp->bmp->height;
	swidth = bmp->bmp->bitmap_callbacks.bitmap_get_bpp(bmp->bmp->bitmap) *
			bmp->bmp->width;
	c->size += (swidth * bmp->bmp->height) + 16 + 44;

	/* set title text */
	title = messages_get_buff("BMPTitle",
			nsurl_access_leaf(llcache_handle_get_url(c->llcache)),
			c->width, c->height);
	if (title != NULL) {
		content__set_title(c, title);
		free(title);
	}

	/* exit as a success */
	bmp->bitmap = bmp->bmp->bitmap;
	bitmap_modified(bmp->bitmap);

	content_set_ready(c);
	content_set_done(c);

	/* Done: update status bar */
	content_set_status(c, "");
	return true;
}

static bool nsbmp_redraw(struct content *c, struct content_redraw_data *data,
		const struct rect *clip, const struct redraw_context *ctx)
{
	nsbmp_content *bmp = (nsbmp_content *) c;
	bitmap_flags_t flags = BITMAPF_NONE;

	if (bmp->bmp->decoded == false)
		if (bmp_decode(bmp->bmp) != BMP_OK)
			return false;

	bmp->bitmap = bmp->bmp->bitmap;

	if (data->repeat_x)
		flags |= BITMAPF_REPEAT_X;
	if (data->repeat_y)
		flags |= BITMAPF_REPEAT_Y;

	return ctx->plot->bitmap(data->x, data->y, data->width, data->height,
			bmp->bitmap, data->background_colour, flags);
}

static void nsbmp_destroy(struct content *c)
{
	nsbmp_content *bmp = (nsbmp_content *) c;

	bmp_finalise(bmp->bmp);
	free(bmp->bmp);
}

static nserror nsbmp_clone(const struct content *old, struct content **newc)
{
	nsbmp_content *new_bmp;
	nserror error;

	new_bmp = calloc(1, sizeof(nsbmp_content));
	if (new_bmp == NULL)
		return NSERROR_NOMEM;

	error = content__clone(old, &new_bmp->base);
	if (error != NSERROR_OK) {
		content_destroy(&new_bmp->base);
		return error;
	}

	/* We "clone" the old content by replaying creation and conversion */
	error = nsbmp_create_bmp_data(new_bmp);
	if (error != NSERROR_OK) {
		content_destroy(&new_bmp->base);
		return error;
	}

	if (old->status == CONTENT_STATUS_READY ||
			old->status == CONTENT_STATUS_DONE) {
		if (nsbmp_convert(&new_bmp->base) == false) {
			content_destroy(&new_bmp->base);
			return NSERROR_CLONE_FAILED;
		}
	}

	*newc = (struct content *) new_bmp;

	return NSERROR_OK;
}

static void *nsbmp_get_internal(const struct content *c, void *context)
{
	nsbmp_content *bmp = (nsbmp_content *)c;

	return bmp->bitmap;
}

static content_type nsbmp_content_type(void)
{
	return CONTENT_IMAGE;
}

static const content_handler nsbmp_content_handler = {
	.create = nsbmp_create,
	.data_complete = nsbmp_convert,
	.destroy = nsbmp_destroy,
	.redraw = nsbmp_redraw,
	.clone = nsbmp_clone,
	.get_internal = nsbmp_get_internal,
	.type = nsbmp_content_type,
	.no_share = false,
};

static const char *nsbmp_types[] = {
	"application/bmp",
	"application/preview",
	"application/x-bmp",
	"application/x-win-bitmap",
	"image/bmp",
	"image/ms-bmp",
	"image/x-bitmap",
	"image/x-bmp",
	"image/x-ms-bmp",
	"image/x-win-bitmap",
	"image/x-windows-bmp",
	"image/x-xbitmap"
};

CONTENT_FACTORY_REGISTER_TYPES(nsbmp, nsbmp_types, nsbmp_content_handler);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
IItemReuseStrategy (Wicket Parent 1.5.7 API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.wicket.markup.repeater.IItemReuseStrategy interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.wicket.markup.repeater

Interface IItemReuseStrategy

All Superinterfaces:
IClusterable, Serializable

All Known Implementing Classes:
DefaultItemReuseStrategy, ReuseIfModelsEqualStrategy

public interface IItemReuseStrategy
extends IClusterable

Interface for item reuse strategies.

 Notice: Child items will be rendered in the order they are provided by the returned
 iterator, so it is important that the strategy preserve this order

Author:

Igor Vaynberg (ivaynberg)

Method Summary

<T> Iterator<Item<T>>

getItems(IItemFactory<T> factory,
         Iterator<IModel<T>> newModels,
         Iterator<Item<T>> existingItems)

          Returns an iterator over items that will be added to the view.

Method Detail

getItems

<T> Iterator<Item<T>> getItems(IItemFactory<T> factory,
                               Iterator<IModel<T>> newModels,
                               Iterator<Item<T>> existingItems)

Returns an iterator over items that will be added to the view. The iterator needs to return
 all the items because the old ones are removed prior to the new ones added.

Type Parameters:
T - type of Item
Parameters:
factory - implementation of IItemFactory
newModels - iterator over models for items
existingItems - iterator over child items

Returns:
iterator over items that will be added after all the old items are moved.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2006-2012 Apache Software Foundation. All Rights Reserved.