text:
#include "extensions/filters/network/kafka/tagged_fields.h"

#include "test/extensions/filters/network/kafka/serialization_utilities.h"

namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace Kafka {
namespace SerializationTest {

/**
 * Tests in this file are supposed to check whether serialization operations
 * on Kafka-primitive types (ints, strings, arrays) are behaving correctly.
 */

// Freshly created deserializers should not be ready.
#define TEST_EmptyDeserializerShouldNotBeReady(DeserializerClass)                                  \
  TEST(DeserializerClass, EmptyBufferShouldNotBeReady) {                                           \
    const DeserializerClass testee{};                                                              \
    ASSERT_EQ(testee.ready(), false);                                                              \
  }

TEST_EmptyDeserializerShouldNotBeReady(Int8Deserializer);
TEST_EmptyDeserializerShouldNotBeReady(Int16Deserializer);
TEST_EmptyDeserializerShouldNotBeReady(Int32Deserializer);
TEST_EmptyDeserializerShouldNotBeReady(UInt32Deserializer);
TEST_EmptyDeserializerShouldNotBeReady(Int64Deserializer);
TEST_EmptyDeserializerShouldNotBeReady(BooleanDeserializer);
TEST_EmptyDeserializerShouldNotBeReady(VarUInt32Deserializer);

TEST_EmptyDeserializerShouldNotBeReady(StringDeserializer);
TEST_EmptyDeserializerShouldNotBeReady(CompactStringDeserializer);
TEST_EmptyDeserializerShouldNotBeReady(NullableStringDeserializer);
TEST_EmptyDeserializerShouldNotBeReady(NullableCompactStringDeserializer);
TEST_EmptyDeserializerShouldNotBeReady(BytesDeserializer);
TEST_EmptyDeserializerShouldNotBeReady(CompactBytesDeserializer);
TEST_EmptyDeserializerShouldNotBeReady(NullableBytesDeserializer);

TEST(ArrayDeserializer, EmptyBufferShouldNotBeReady) {
  // given
  const ArrayDeserializer<Int8Deserializer> testee{};
  // when, then
  ASSERT_EQ(testee.ready(), false);
}

TEST(CompactArrayDeserializer, EmptyBufferShouldNotBeReady) {
  // given
  const CompactArrayDeserializer<Int32Deserializer> testee{};
  // when, then
  ASSERT_EQ(testee.ready(), false);
}

TEST(NullableArrayDeserializer, EmptyBufferShouldNotBeReady) {
  // given
  const NullableArrayDeserializer<Int8Deserializer> testee{};
  // when, then
  ASSERT_EQ(testee.ready(), false);
}

TEST(NullableCompactArrayDeserializer, EmptyBufferShouldNotBeReady) {
  // given
  const NullableCompactArrayDeserializer<Int32Deserializer> testee{};
  // when, then
  ASSERT_EQ(testee.ready(), false);
}

// Extracted test for numeric buffers.
#define TEST_DeserializerShouldDeserialize(BufferClass, DataClass, Value)                          \
  TEST(DataClass, ShouldConsumeCorrectAmountOfData) {                                              \
    /* given */                                                                                \
    const DataClass value = Value;                                                                 \
    serializeThenDeserializeAndCheckEquality<BufferClass>(value);                                  \
  }

TEST_DeserializerShouldDeserialize(Int8Deserializer, int8_t, 42);
TEST_DeserializerShouldDeserialize(Int16Deserializer, int16_t, 42);
TEST_DeserializerShouldDeserialize(Int32Deserializer, int32_t, 42);
TEST_DeserializerShouldDeserialize(UInt32Deserializer, uint32_t, 42);
TEST_DeserializerShouldDeserialize(Int64Deserializer, int64_t, 42);
TEST_DeserializerShouldDeserialize(BooleanDeserializer, bool, true);

EncodingContext encoder{-1}; // Provided api_version does not matter for primitive types.

// Variable-length uint32_t tests.

TEST(VarUInt32Deserializer, ShouldDeserialize) {
  const uint32_t value = 0;
  serializeCompactThenDeserializeAndCheckEquality<VarUInt32Deserializer>(value);
}

TEST(VarUInt32Deserializer, ShouldDeserializeMaxUint32) {
  const uint32_t value = std::numeric_limits<uint32_t>::max();
  serializeCompactThenDeserializeAndCheckEquality<VarUInt32Deserializer>(value);
}

TEST(VarUInt32Deserializer, ShouldDeserializeEdgeValues) {
  // Each of these values should fit in 1, 2, 3, 4 bytes.
  std::vector<uint32_t> values = {0x7f, 0x3fff, 0x1fffff, 0xfffffff};
  for (auto i = 0; i < static_cast<int>(values.size()); ++i) {
    // given
    Buffer::OwnedImpl buffer;

    // when
    const uint32_t written = encoder.encodeCompact(values[i], buffer);

    // then
    ASSERT_EQ(written, i + 1);
    absl::string_view data = {getRawData(buffer), 1024};
    // All bits in lower bytes need to be set.
    for (auto j = 0; j + 1 < i; ++j) {
      ASSERT_EQ(static_cast<uint8_t>(data[j]), 0xFF);
    }
    // Highest bit in last byte needs to be clear (end marker).
    ASSERT_EQ(static_cast<uint8_t>(data[i]), 0x7F);
  }
}

TEST(VarUInt32Deserializer, ShouldSerializeMaxUint32Properly) {
  // given
  Buffer::OwnedImpl buffer;

  // when
  const uint32_t value = std::numeric_limits<uint32_t>::max();
  const uint32_t result = encoder.encodeCompact(value, buffer);

  // then
  ASSERT_EQ(result, 5);
  absl::string_view data = {getRawData(buffer), 1024};
  ASSERT_EQ(static_cast<uint8_t>(data[0]), 0xFF); // Bits 1-7 (starting at 1).
  ASSERT_EQ(static_cast<uint8_t>(data[1]), 0xFF); // Bits 8-14.
  ASSERT_EQ(static_cast<uint8_t>(data[2]), 0xFF); // Bits 15-21.
  ASSERT_EQ(static_cast<uint8_t>(data[3]), 0xFF); // Bits 22-28.
  ASSERT_EQ(static_cast<uint8_t>(data[4]), 0x0F); // Bits 29-32.
}

TEST(VarUInt32Deserializer, ShouldThrowIfNoEndWith5Bytes) {
  // given
  VarUInt32Deserializer testee;
  Buffer::OwnedImpl buffer;

  // The buffer makes no sense, it's 5 times 0xFF, while varint encoding ensures that in the worst
  // case 5th byte has the highest bit clear.
  for (int i = 0; i < 5; ++i) {
    const uint8_t all_bits_set = 0xFF;
    buffer.add(&all_bits_set, sizeof(all_bits_set));
  }

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// String tests.

TEST(StringDeserializer, ShouldDeserialize) {
  const std::string value = "sometext";
  serializeThenDeserializeAndCheckEquality<StringDeserializer>(value);
}

TEST(StringDeserializer, ShouldDeserializeEmptyString) {
  const std::string value = "";
  serializeThenDeserializeAndCheckEquality<StringDeserializer>(value);
}

TEST(StringDeserializer, ShouldThrowOnInvalidLength) {
  // given
  StringDeserializer testee;
  Buffer::OwnedImpl buffer;

  int16_t len = -1; // STRING accepts length >= 0.
  encoder.encode(len, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Compact string tests.

TEST(CompactStringDeserializer, ShouldDeserialize) {
  const std::string value = "sometext";
  serializeCompactThenDeserializeAndCheckEquality<CompactStringDeserializer>(value);
}

TEST(CompactStringDeserializer, ShouldDeserializeEmptyString) {
  const std::string value = "";
  serializeCompactThenDeserializeAndCheckEquality<CompactStringDeserializer>(value);
}

TEST(CompactStringDeserializer, ShouldThrowOnInvalidLength) {
  // given
  CompactStringDeserializer testee;
  Buffer::OwnedImpl buffer;

  const uint32_t len = 0; // COMPACT_STRING requires length >= 1.
  encoder.encodeCompact(len, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Nullable string tests.

TEST(NullableStringDeserializer, ShouldDeserializeString) {
  // given
  const NullableString value{"sometext"};
  serializeThenDeserializeAndCheckEquality<NullableStringDeserializer>(value);
}

TEST(NullableStringDeserializer, ShouldDeserializeEmptyString) {
  // given
  const NullableString value{""};
  serializeThenDeserializeAndCheckEquality<NullableStringDeserializer>(value);
}

TEST(NullableStringDeserializer, ShouldDeserializeAbsentString) {
  // given
  const NullableString value = absl::nullopt;
  serializeThenDeserializeAndCheckEquality<NullableStringDeserializer>(value);
}

TEST(NullableStringDeserializer, ShouldThrowOnInvalidLength) {
  // given
  NullableStringDeserializer testee;
  Buffer::OwnedImpl buffer;

  int16_t len = -2; // -1 is OK for NULLABLE_STRING.
  encoder.encode(len, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Nullable compact string tests.

TEST(NullableCompactStringDeserializer, ShouldDeserializeString) {
  // given
  const NullableString value{"sometext"};
  serializeCompactThenDeserializeAndCheckEquality<NullableCompactStringDeserializer>(value);
}

TEST(NullableCompactStringDeserializer, ShouldDeserializeEmptyString) {
  // given
  const NullableString value{""};
  serializeCompactThenDeserializeAndCheckEquality<NullableCompactStringDeserializer>(value);
}

TEST(NullableCompactStringDeserializer, ShouldDeserializeAbsentString) {
  // given
  const NullableString value = absl::nullopt;
  serializeCompactThenDeserializeAndCheckEquality<NullableCompactStringDeserializer>(value);
}

// Byte array tests.

TEST(BytesDeserializer, ShouldDeserialize) {
  const Bytes value{'a', 'b', 'c', 'd'};
  serializeThenDeserializeAndCheckEquality<BytesDeserializer>(value);
}

TEST(BytesDeserializer, ShouldDeserializeEmptyBytes) {
  const Bytes value{};
  serializeThenDeserializeAndCheckEquality<BytesDeserializer>(value);
}

TEST(BytesDeserializer, ShouldThrowOnInvalidLength) {
  // given
  BytesDeserializer testee;
  Buffer::OwnedImpl buffer;

  const int32_t bytes_length = -1; // BYTES accepts length >= 0.
  encoder.encode(bytes_length, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Compact byte array tests.

TEST(CompactBytesDeserializer, ShouldDeserialize) {
  const Bytes value{'a', 'b', 'c', 'd'};
  serializeCompactThenDeserializeAndCheckEquality<CompactBytesDeserializer>(value);
}

TEST(CompactBytesDeserializer, ShouldDeserializeEmptyBytes) {
  const Bytes value{};
  serializeCompactThenDeserializeAndCheckEquality<CompactBytesDeserializer>(value);
}

TEST(CompactBytesDeserializer, ShouldThrowOnInvalidLength) {
  // given
  CompactBytesDeserializer testee;
  Buffer::OwnedImpl buffer;

  const uint32_t bytes_length = 0; // COMPACT_BYTES requires length >= 1.
  encoder.encodeCompact(bytes_length, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Nullable byte array tests.

TEST(NullableBytesDeserializer, ShouldDeserialize) {
  const NullableBytes value{{'a', 'b', 'c', 'd'}};
  serializeThenDeserializeAndCheckEquality<NullableBytesDeserializer>(value);
}

TEST(NullableBytesDeserializer, ShouldDeserializeEmptyBytes) {
  // gcc refuses to initialize optional with empty vector with value{{}}
  const NullableBytes value = {{}};
  serializeThenDeserializeAndCheckEquality<NullableBytesDeserializer>(value);
}

TEST(NullableBytesDeserializer, ShouldDeserializeNullBytes) {
  const NullableBytes value = absl::nullopt;
  serializeThenDeserializeAndCheckEquality<NullableBytesDeserializer>(value);
}

TEST(NullableBytesDeserializer, ShouldThrowOnInvalidLength) {
  // given
  NullableBytesDeserializer testee;
  Buffer::OwnedImpl buffer;

  const int32_t bytes_length = -2; // -1 is OK for NULLABLE_BYTES.
  encoder.encode(bytes_length, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Generic array tests.

TEST(ArrayDeserializer, ShouldConsumeCorrectAmountOfData) {
  const std::vector<std::string> value{{"aaa", "bbbbb", "cc", "d", "e", "ffffffff"}};
  serializeThenDeserializeAndCheckEquality<ArrayDeserializer<StringDeserializer>>(value);
}

TEST(ArrayDeserializer, ShouldThrowOnInvalidLength) {
  // given
  ArrayDeserializer<StringDeserializer> testee;
  Buffer::OwnedImpl buffer;

  const int32_t len = -1; // ARRAY accepts length >= 0.
  encoder.encode(len, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Compact generic array tests.

TEST(CompactArrayDeserializer, ShouldConsumeCorrectAmountOfData) {
  const std::vector<int32_t> value{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}};
  serializeCompactThenDeserializeAndCheckEquality<CompactArrayDeserializer<Int32Deserializer>>(
      value);
}

TEST(CompactArrayDeserializer, ShouldThrowOnInvalidLength) {
  // given
  CompactArrayDeserializer<Int8Deserializer> testee;
  Buffer::OwnedImpl buffer;

  const uint32_t len = 0; // COMPACT_ARRAY accepts length >= 1.
  encoder.encodeCompact(len, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Generic nullable array tests.

TEST(NullableArrayDeserializer, ShouldConsumeCorrectAmountOfData) {
  const NullableArray<std::string> value{{"aaa", "bbbbb", "cc", "d", "e", "ffffffff"}};
  serializeThenDeserializeAndCheckEquality<NullableArrayDeserializer<StringDeserializer>>(value);
}

TEST(NullableArrayDeserializer, ShouldConsumeNullArray) {
  const NullableArray<std::string> value = absl::nullopt;
  serializeThenDeserializeAndCheckEquality<NullableArrayDeserializer<StringDeserializer>>(value);
}

TEST(NullableArrayDeserializer, ShouldThrowOnInvalidLength) {
  // given
  NullableArrayDeserializer<StringDeserializer> testee;
  Buffer::OwnedImpl buffer;

  const int32_t len = -2; // -1 is OK for NULLABLE_ARRAY.
  encoder.encode(len, buffer);

  absl::string_view data = {getRawData(buffer), 1024};

  // when
  // then
  EXPECT_THROW(testee.feed(data), EnvoyException);
}

// Compact nullable generic array tests.

TEST(NullableCompactArrayDeserializer, ShouldConsumeCorrectAmountOfData) {
  const NullableArray<int32_t> value{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}};
  serializeCompactThenDeserializeAndCheckEquality<
      NullableCompactArrayDeserializer<Int32Deserializer>>(value);
}

TEST(NullableCompactArrayDeserializer, ShouldConsumeNullArray) {
  const NullableArray<int32_t> value = absl::nullopt;
  serializeCompactThenDeserializeAndCheckEquality<
      NullableCompactArrayDeserializer<Int32Deserializer>>(value);
}

// Tagged fields.

TEST(TaggedFieldDeserializer, ShouldConsumeCorrectAmountOfData) {
  const TaggedField value{200, Bytes{1, 2, 3, 4, 5, 6}};
  serializeCompactThenDeserializeAndCheckEquality<TaggedFieldDeserializer>(value);
}

TEST(TaggedFieldsDeserializer, ShouldConsumeCorrectAmountOfData) {
  std::vector<TaggedField> fields;
  for (uint32_t i = 0; i < 200; ++i) {
    const TaggedField tagged_field = {i, Bytes{1, 2, 3, 4}};
    fields.push_back(tagged_field);
  }
  const TaggedFields value{fields};
  serializeCompactThenDeserializeAndCheckEquality<TaggedFieldsDeserializer>(value);
}

} // namespace SerializationTest
} // namespace Kafka
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl.statements.arguments;

import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrSpreadArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiElementImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;

/**
 * @author Max Medvedev
 */
public class GrSpreadArgumentImpl extends GroovyPsiElementImpl implements GrSpreadArgument {
  public GrSpreadArgumentImpl(@NotNull ASTNode node) {
    super(node);
  }

  @NotNull
  @Override
  public GrExpression getArgument() {
    return findNotNullChildByClass(GrExpression.class);
  }

  @Override
  public PsiType getType() {
    return getArgument().getType();
  }

  @Override
  public PsiType getNominalType() {
    return getType();
  }

  @Override
  public GrExpression replaceWithExpression(@NotNull GrExpression expression, boolean removeUnnecessaryParentheses) {
    return PsiImplUtil.replaceExpression(this, expression, removeUnnecessaryParentheses);
  }

  @Override
  public String toString() {
    return "Spread argument";
  }

  @Override
  public void accept(@NotNull GroovyElementVisitor visitor) {
    visitor.visitSpreadArgument(this);
  }
}

redpajama_set_name: RedPajamaGithub


text:
extern int debug_logging_mode;

#pragma pack(push,2)

typedef struct {
    char ckID [4];
    int64_t ckDataSize;
} DFFChunkHeader;

typedef struct {
    char ckID [4];
    int64_t ckDataSize;
    char formType [4];
} DFFFileHeader;

typedef struct {
    char ckID [4];
    int64_t ckDataSize;
    uint32_t version;
} DFFVersionChunk;

typedef struct {
    char ckID [4];
    int64_t ckDataSize;
    uint32_t sampleRate;
} DFFSampleRateChunk;

typedef struct {
    char ckID [4];
    int64_t ckDataSize;
    uint16_t numChannels;
} DFFChannelsHeader;

typedef struct {
    char ckID [4];
    int64_t ckDataSize;
    char compressionType [4];
} DFFCompressionHeader;

#pragma pack(pop)

#define DFFChunkHeaderFormat "4D"
#define DFFFileHeaderFormat "4D4"
#define DFFVersionChunkFormat "4DL"
#define DFFSampleRateChunkFormat "4DL"
#define DFFChannelsHeaderFormat "4DS"
#define DFFCompressionHeaderFormat "4D4"

int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
    int64_t infilesize, total_samples;
    DFFFileHeader dff_file_header;
    DFFChunkHeader dff_chunk_header;
    uint32_t bcount;

    infilesize = DoGetFileSize (infile);
    memcpy (&dff_file_header, fourcc, 4);

    if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
        bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
            error_line ("%s is not a valid .DFF file!", infilename);
            return WAVPACK_SOFT_ERROR;
    }
    else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
        !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
            error_line ("%s", WavpackGetErrorMessage (wpc));
            return WAVPACK_SOFT_ERROR;
    }

#if 1   // this might be a little too picky...
    WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);

    if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
        dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
            error_line ("%s is not a valid .DFF file (by total size)!", infilename);
            return WAVPACK_SOFT_ERROR;
    }

    if (debug_logging_mode)
        error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);

#endif

    // loop through all elements of the DSDIFF header
    // (until the data chuck) and copy them to the output file

    while (1) {
        if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
            bcount != sizeof (DFFChunkHeader)) {
                error_line ("%s is not a valid .DFF file!", infilename);
                return WAVPACK_SOFT_ERROR;
        }
        else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
            !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
                error_line ("%s", WavpackGetErrorMessage (wpc));
                return WAVPACK_SOFT_ERROR;
        }

        WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);

        if (debug_logging_mode)
            error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);

        if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
            uint32_t version;

            if (dff_chunk_header.ckDataSize != sizeof (version) ||
                !DoReadFile (infile, &version, sizeof (version), &bcount) ||
                bcount != sizeof (version)) {
                    error_line ("%s is not a valid .DFF file!", infilename);
                    return WAVPACK_SOFT_ERROR;
            }
            else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
                !WavpackAddWrapper (wpc, &version, sizeof (version))) {
                    error_line ("%s", WavpackGetErrorMessage (wpc));
                    return WAVPACK_SOFT_ERROR;
            }

            WavpackBigEndianToNative (&version, "L");

            if (debug_logging_mode)
                error_line ("dsdiff file version = 0x%08x", version);
        }
        else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
            char *prop_chunk;

            if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {
                error_line ("%s is not a valid .DFF file!", infilename);
                return WAVPACK_SOFT_ERROR;
            }

            if (debug_logging_mode)
                error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize);

            prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);

            if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
                bcount != dff_chunk_header.ckDataSize) {
                    error_line ("%s is not a valid .DFF file!", infilename);
                    free (prop_chunk);
                    return WAVPACK_SOFT_ERROR;
            }
            else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
                !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
                    error_line ("%s", WavpackGetErrorMessage (wpc));
                    free (prop_chunk);
                    return WAVPACK_SOFT_ERROR;
            }

            if (!strncmp (prop_chunk, "SND ", 4)) {
                char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
                uint16_t numChannels = 0, chansSpecified, chanMask = 0;
                uint32_t sampleRate = 0;

                while (eptr - cptr >= sizeof (dff_chunk_header)) {
                    memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
                    cptr += sizeof (dff_chunk_header);
                    WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);

                    if (dff_chunk_header.ckDataSize > 0 && dff_chunk_header.ckDataSize <= eptr - cptr) {
                        if (!strncmp (dff_chunk_header.ckID, "FS  ", 4) && dff_chunk_header.ckDataSize == 4) {
                            memcpy (&sampleRate, cptr, sizeof (sampleRate));
                            WavpackBigEndianToNative (&sampleRate, "L");
                            cptr += dff_chunk_header.ckDataSize;

                            if (debug_logging_mode)
                                error_line ("got sample rate of %u Hz", sampleRate);
                        }
                        else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
                            memcpy (&numChannels, cptr, sizeof (numChannels));
                            WavpackBigEndianToNative (&numChannels, "S");
                            cptr += sizeof (numChannels);

                            chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;

                            if (numChannels < chansSpecified || numChannels < 1 || numChannels > WAVPACK_MAX_CLI_CHANS) {
                                error_line ("%s is not a valid .DFF file!", infilename);
                                free (prop_chunk);
                                return WAVPACK_SOFT_ERROR;
                            }

                            while (chansSpecified--) {
                                if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
                                    chanMask |= 0x1;
                                else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
                                    chanMask |= 0x2;
                                else if (!strncmp (cptr, "LS  ", 4))
                                    chanMask |= 0x10;
                                else if (!strncmp (cptr, "RS  ", 4))
                                    chanMask |= 0x20;
                                else if (!strncmp (cptr, "C   ", 4))
                                    chanMask |= 0x4;
                                else if (!strncmp (cptr, "LFE ", 4))
                                    chanMask |= 0x8;
                                else
                                    if (debug_logging_mode)
                                        error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);

                                cptr += 4;
                            }

                            if (debug_logging_mode)
                                error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
                        }
                        else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
                            if (strncmp (cptr, "DSD ", 4)) {
                                error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
                                    cptr [0], cptr [1], cptr [2], cptr [3]);
                                free (prop_chunk);
                                return WAVPACK_SOFT_ERROR;
                            }

                            cptr += dff_chunk_header.ckDataSize;
                        }
                        else {
                            if (debug_logging_mode)
                                error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
                                    dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);

                            cptr += dff_chunk_header.ckDataSize;
                        }
                    }
                    else {
                        error_line ("%s is not a valid .DFF file!", infilename);
                        free (prop_chunk);
                        return WAVPACK_SOFT_ERROR;
                    }
                }

                if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
                    error_line ("this DSDIFF file already has channel order information!");
                    free (prop_chunk);
                    return WAVPACK_SOFT_ERROR;
                }
                else if (chanMask)
                    config->channel_mask = chanMask;

                config->bits_per_sample = 8;
                config->bytes_per_sample = 1;
                config->num_channels = numChannels;
                config->sample_rate = sampleRate / 8;
                config->qmode |= QMODE_DSD_MSB_FIRST;
            }
            else if (debug_logging_mode)
                error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
                    prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);

            free (prop_chunk);
        }
        else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {

            if (!config->num_channels || !config->sample_rate) {
                error_line ("%s is not a valid .DFF file!", infilename);
                return WAVPACK_SOFT_ERROR;
            }

            total_samples = dff_chunk_header.ckDataSize / config->num_channels;

            if (total_samples <= 0 || total_samples > MAX_WAVPACK_SAMPLES) {
                error_line ("%s is not a valid .DFF file!", infilename);
                return WAVPACK_SOFT_ERROR;
            }

            break;
        }
        else {          // just copy unknown chunks to output file

            int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
            char *buff;

            if (bytes_to_copy < 0 || bytes_to_copy > 4194304) {
                error_line ("%s is not a valid .DFF file!", infilename);
                return WAVPACK_SOFT_ERROR;
            }

            buff = malloc (bytes_to_copy);

            if (debug_logging_mode)
                error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
                    dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
                    dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);

            if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
                bcount != bytes_to_copy ||
                (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
                !WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
                    error_line ("%s", WavpackGetErrorMessage (wpc));
                    free (buff);
                    return WAVPACK_SOFT_ERROR;
            }

            free (buff);
        }
    }

    if (debug_logging_mode)
        error_line ("setting configuration with %lld samples", total_samples);

    if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
        error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
        return WAVPACK_SOFT_ERROR;
    }

    return WAVPACK_NO_ERROR;
}


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="https://unpkg.com/jspsych@7.3.1/css/jspsych.css" />
    <link rel="stylesheet" href="docs-demo.css" type="text/css" />


text: Ultra thin polymerjs 1.0 wrapper.


text:
id: cf1111c1c11feddfaeb1bdef
title: Iterate with JavaScript While Loops
challengeType: 1
videoUrl: ''
localeTitle: 'Итерации с помощью JavaScript, в то время как циклы'
---

## Description

 Вы можете запустить один и тот же код несколько раз, используя цикл. Первый тип цикла мы узнаем , что называется « в while » цикл , так как он работает « а» заданное условие истинно , и не остановится , как только это условие уже не так.
 var ourArray = [];
 var i = 0;
 тогда как (i <5) {
 ourArray.push (я);
 я ++;
 }
 Попробуем получить цикл while для работы, нажав значения в массив.

## Instructions

 Нажмите цифры от 0 до 4 , чтобы myArray используя while цикл.

## Tests

```yml
tests:
  - text: Вы должны использовать <code>while</code> петлю для этого.
    testString: 'assert(code.match(/while/g), "You should be using a <code>while</code> loop for this.");'
  - text: '<code>myArray</code> должен равняться <code>[0,1,2,3,4]</code> .'
    testString: 'assert.deepEqual(myArray, [0,1,2,3,4], "<code>myArray</code> should equal <code>[0,1,2,3,4]</code>.");'

```

## Challenge Seed

```js
// Setup
var myArray = [];

// Only change code below this line.

```

### After Test

```js
console.info('after the test');
```

## Solution

```js
// solution required
```


text:
using Avalonia.Markup.Xaml.PortableXaml;
using Portable.Xaml.Markup;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ComponentModel;

namespace Portable.Xaml.ComponentModel
{
    internal static class TypeDescriptorExtensions
    {
        /// <summary>
        /// Gets the service from ITypeDescriptorContext
        /// usually in TypeConverter in xaml reader context
        /// examples:
        /// context.GetService<IXamlTypeResolver>()
        /// context.GetService<IXamlNamespaceResolver>()
        /// context.GetService<IXamlNameProvider>()
        /// context.GetService<INamespacePrefixLookup>()
        /// context.GetService<IXamlSchemaContextProvider>()
        /// context.GetService<IRootObjectProvider>()
        /// context.GetService<IProvideValueTarget>()
        /// </summary>
        /// <typeparam name="T">Service Type</typeparam>
        /// <param name="ctx">The TypeDescriptor context.</param>
        /// <returns></returns>
        public static T GetService<T>(this ITypeDescriptorContext ctx) where T : class
        {
            return ctx.GetService(typeof(T)) as T;
        }

        public static Type ResolveType(this ITypeDescriptorContext ctx, string namespacePrefix, string type)
        {
            var tr = ctx.GetService<IXamlTypeResolver>();

            string name = string.IsNullOrEmpty(namespacePrefix) ? type : $"{namespacePrefix}:{type}";

            return tr?.Resolve(name);
        }

        public static T GetFirstAmbientValue<T>(this ITypeDescriptorContext ctx) where T : class
        {
            var amb = ctx.GetService<IAmbientProvider>();
            var sc = ctx.GetService<IXamlSchemaContextProvider>().SchemaContext;

            return amb.GetFirstAmbientValue(sc.GetXamlType(typeof(T))) as T;
        }

        public static T GetLastOrDefaultAmbientValue<T>(this ITypeDescriptorContext ctx) where T : class
        {
            return ctx.GetAllambientValues<T>().LastOrDefault() as T;
        }

        public static IEnumerable<T> GetAllambientValues<T>(this ITypeDescriptorContext ctx) where T : class
        {
            var amb = ctx.GetService<IAmbientProvider>();
            var sc = ctx.GetService<IXamlSchemaContextProvider>().SchemaContext;

            return amb.GetAllAmbientValues(sc.GetXamlType(typeof(T))).OfType<T>();
        }

        public static Uri GetBaseUri(this ITypeDescriptorContext ctx)
        {
            return ctx.GetWriterSettings()?.Context?.BaseUri;
        }

        public static Assembly GetLocalAssembly(this ITypeDescriptorContext ctx)
        {
            return ctx.GetWriterSettings()?.Context?.LocalAssembly;
        }

        public static AvaloniaXamlContext GetAvaloniaXamlContext(this ITypeDescriptorContext ctx)
        {
            return ctx.GetWriterSettings()?.Context;
        }

        public static XamlObjectWriterSettings WithContext(this XamlObjectWriterSettings settings, AvaloniaXamlContext context)
        {
            return new AvaloniaXamlObjectWriterSettings(settings, context);
        }

        private static AvaloniaXamlObjectWriterSettings GetWriterSettings(this ITypeDescriptorContext ctx)
        {
            return ctx.GetService<IXamlObjectWriterFactory>().GetParentSettings() as AvaloniaXamlObjectWriterSettings;
        }

        private class AvaloniaXamlObjectWriterSettings : XamlObjectWriterSettings
        {
            public AvaloniaXamlObjectWriterSettings(XamlObjectWriterSettings settings, AvaloniaXamlContext context)
                : base(settings)
            {
                Context = context;
            }

            public AvaloniaXamlContext Context { get; }
        }
    }
}


text:
package com.wabbit.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseInstallation;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.wabbit.abstracts.Enums;
import com.wabbit.abstracts.ParseMemCache;
import com.wabbit.application.BaseApp;
import com.wabbit.libraries.remoting.FBMgr;
import com.wabbit.messenger.R;

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

public class StartActivity extends BaseActivity{
	private Button button;

    @Override
	public void onCreate(Bundle savedExtras){
		super.onCreate(savedExtras);

		setContentView(R.layout.login_layout);

		button = (Button)findViewById(R.id.sign_in_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApp.getApp().mixtrack("Click login");
                if(BaseApp.getApp().isNetworkConnected() == false){
                    Toast.makeText(StartActivity.this, "No internet connection!", Toast.LENGTH_SHORT).show();
                    return;
                }
                //Facebook permissions
                List<String> permissions = new ArrayList<String>();
//                permissions.add("user_photos");
                ParseFacebookUtils.logIn(permissions, StartActivity.this, new LogInCallback() {
                    @Override
                    public void done(ParseUser user, ParseException err) {
                        if (user == null) {
                            Log.d("MyApp", "Uh oh. The user canceled the Facebook login.");
                            Toast.makeText(StartActivity.this, "Login canceled", Toast.LENGTH_LONG).show();
                            BaseApp.getApp().mixtrack("Login canceled");
                        } else if (user.isNew()) {
                            Log.d("MyApp", "User signed up and logged in through Facebook!");
                            BaseApp.getApp().mixtrack("Sign up");
                            collectUserData();
                        } else {
                            Log.d("MyApp", "User logged in through Facebook!");
                            BaseApp.getApp().mixtrack("Login complete");
                            collectUserData();
                        }
                    }
                });
            }
        });
	}
    @Override
    public void onResume(){
        super.onResume();
        BaseApp.getApp().mixtrack("Start app");
        if(ParseUser.getCurrentUser() != null){
            collectUserData();
            return ;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data);
    }

    private ProgressDialog progress;
    private void collectUserData(){
        ParseMemCache.gi().put(ParseUser.getCurrentUser(), false);
        /**BUG FIX: trying to show progress on paused activity*/
        if(isRunning())
            progress = ProgressDialog.show(this, "Please wait", "Logging you in...", true, false);
        FBMgr.gi().meRequest(new Runnable() {
            @Override
            public void run() {
                if(FBMgr.gi().getUser() == null) {
                    Toast.makeText(StartActivity.this,"Couldn't connect to facebook", Toast.LENGTH_LONG).show();
                    progress.dismiss();
                    return;
                }
//                If user has no photo
//                if(ParseUser.getCurrentUser().get(Enums.ParseKey.USER_FB_PHOTOS) == null){
//                    FBMgr.gi().getPhotos();
//                }
                //Save name and fbid if them weren't saved before
                if(ParseUser.getCurrentUser().get(Enums.ParseKey.USER_FBID) == null ||
                        ParseUser.getCurrentUser().getBoolean(Enums.ParseKey.USER_VISIBLE) == false){
                    ParseUser.getCurrentUser().put(Enums.ParseKey.USER_FBID, FBMgr.gi().getUser().getId());
                    ParseUser.getCurrentUser().put(Enums.ParseKey.USER_NAME, FBMgr.gi().getUser().getName());

                    //visible
                    if(ParseUser.getCurrentUser().getBoolean(Enums.ParseKey.USER_VISIBLE) == false)
                        ParseUser.getCurrentUser().put(Enums.ParseKey.USER_VISIBLE, true);

                    ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            if(e == null)
                                startMainAct();
                            else {
                                e.printStackTrace();
                                Toast.makeText(StartActivity.this,"Couldn't connect to server", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                } else
                    startMainAct();

                // Associate the device with a user
                ParseInstallation installation = ParseInstallation.getCurrentInstallation();
                if(installation.get("user") == null){
                    installation.put(Enums.ParseKey.INSTAL_USER, ParseUser.getCurrentUser());
                    installation.put(Enums.ParseKey.INSTAL_ANDROID_ID, Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
                    installation.saveInBackground();
                }

                dismissProgress();
            }
        });
    }

    private void startMainAct(){
        startActivity(MainActivity.class, true, null);
        finish();
    }

    private void dismissProgress(){
        if(progress != null){
            progress.dismiss();
            progress = null;
        }
    }
}


text:
package org.apache.cloudstack.api.command.admin.offering;

import org.apache.log4j.Logger;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.DiskOfferingResponse;
import org.apache.cloudstack.api.response.SuccessResponse;

import com.cloud.user.Account;

@APICommand(name = "deleteDiskOffering", description = "Updates a disk offering.", responseObject = SuccessResponse.class,
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class DeleteDiskOfferingCmd extends BaseCmd {
    public static final Logger s_logger = Logger.getLogger(DeleteDiskOfferingCmd.class.getName());
    private static final String s_name = "deletediskofferingresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DiskOfferingResponse.class, required = true, description = "ID of the disk offering")
    private Long id;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Long getId() {
        return id;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public long getEntityOwnerId() {
        return Account.ACCOUNT_ID_SYSTEM;
    }

    @Override
    public void execute() {
        boolean result = _configService.deleteDiskOffering(this);
        if (result) {
            SuccessResponse response = new SuccessResponse(getCommandName());
            this.setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete disk offering");
        }
    }
}


text:
'use strict';

var expect = require('chai').expect;
var spec = require('../util.js').setup();

describe('lesshint', function () {
    describe('#maxCharPerLine()', function () {
        it('should have the proper node types', function () {
            var source = '.foo { }';

            return spec.parse(source, function (ast) {
                expect(spec.linter.nodeTypes).to.include(ast.root.type);
            });
        });

        it('should allow files which do not have any lines exceed 10 characters', function () {
            var source = '.foo {}';
            var options = {
                limit: 10
            };

            return spec.parse(source, function (ast) {
            // Set to the limit to 10 characters to simplify test source
                var result = spec.linter.lint(options, ast.root);

                expect(result).to.be.undefined;
            });
        });

        it('should not allow files which have any lines that exceed 10 characters', function () {
            var source = '.foofoofoofoo { }';
            var expected = [{
                column: 0,
                line: 1,
                message: 'Line should not exceed 10 characters, 17 found.'
            }];
            var options = {
                limit: 10
            };

            return spec.parse(source, function (ast) {
                var result = spec.linter.lint(options, ast.root);

                expect(result).to.deep.equal(expected);
            });
        });

        it('should report multiple errors if there are multiple lines exceed characters limit', function () {
            var source = '.foofoofoofoo { }\n.looloolooloo { }';
            var expected = [
                {
                    column: 0,
                    line: 1,
                    message: 'Line should not exceed 10 characters, 17 found.'
                },
                {
                    column: 0,
                    line: 2,
                    message: 'Line should not exceed 10 characters, 17 found.'
                }
            ];
            var options = {
                limit: 10
            };

            return spec.parse(source, function (ast) {
                var result = spec.linter.lint(options, ast.root);

                expect(result).to.deep.equal(expected);
            });
        });

        it('should ignore empty files', function () {
            var source = '';

            return spec.parse(source, function (ast) {
                var result = spec.linter.lint({}, ast.root);

                expect(result).to.be.undefined;
            });
        });
    });
});


text:
import jwt from 'jwt-simple';

const createToken = (user, next) => {
  const payload = {
    sub: user._id
  };
  const token = jwt.encode(payload, 'rainbow');
  return next(token);
};

const decodeToken = (token, next) => {
  const payload = jwt.decode(token, 'rainbow');
  return next(payload);
};

export { createToken, decodeToken };


text:
function initPrimaryLinks(){
  GOVUK.primaryLinks.init('.primary-item');
}
$(initPrimaryLinks);
$(window).on('displayPreviewDone', initPrimaryLinks);

jQuery(function($) {
  $(".select2").select2({
    placeholder: $(this).data('placeholder')
  });

  $(".js-length-counter").each(function(){
    new GOVUK.LengthCounter({$el:$(this)});
  })

  $(".reorderable-document-list").sortable();
});


text:
module CAdmin
  module ApplicationHelper
  end
end


text:
meta:
  title: Skeleton loader component
  description: The v-skeleton-loader component is a versatile tool that can fill many roles within a project. At its heart, the component provides an indication to the user that something is coming but not yet available.
  keywords: skeleton-loader, material loader, bar loader
related:
  - /components/cards/
  - /components/progress-circular/
  - /components/buttons/
---

# Skeleton loaders

The `v-skeleton-loader` component is a versatile tool that can fill many roles within a project.  At its heart, the component provides an indication to the user that something is coming but not yet available. There are over 30 pre-defined options available that can be combined to make custom examples.

<entry-ad />

## Usage

The `v-skeleton-loader` component provides a user with a visual indicator that content is coming / loading. This is better received than traditional full-screen loaders.

<example file="v-skeleton-loader/usage" />

## API

- [v-skeleton-loader](/api/v-skeleton-loader)

<inline-api page="components/skeleton-loaders" />

## Examples

### Misc

#### Boilerplate component

The `v-skeleton-loader` can be used as boilerplate designs when creating mockups. Mix and match various pre-defined options or create your own unique implementations. In this example, we use a custom **data** property to apply the same props to multiple `v-skeleton-loader`'s at once.

<example file="v-skeleton-loader/misc-boilerplate" />

<!-- #### Implementation methods

There are 2 ways that you can utilize the `v-skeleton-component`. The **default slot** or a **v-if** conditional. The built in slot is the most convenient and easiest to use, but generates an extra div once rendered. If the extra div is an issue in your setup, you can utilize a **v-if** conditional with a Vuetify [transition component](/styles/transitions) or a custom one.

<example file="v-skeleton-loader/misc-implementation" /> -->

## Accessibility

By default, the `v-skeleton-loader` component is assigned a [WAI-ARIA](https://www.w3.org/WAI/standards-guidelines/aria/) role of [**alert**](https://www.w3.org/TR/wai-aria/#alert). We augment this role with two aria properties. An [**aria-busy**](https://www.w3.org/TR/wai-aria-1.0/states_and_properties#aria-busy) value of **true** denotes that a widget is missing required owned elements. An [**aria-live**](https://www.w3.org/TR/wai-aria-1.1/#aria-live) value of **polite** sets the screen reader's priority of live regions.

<backmatter />


text:
package apple.arkit;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSCoder;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.protocol.NSCopying;
import apple.foundation.protocol.NSSecureCoding;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.ProtocolClassMethod;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * Collection of fields to give information on geo tracking status.
 */
@Generated
@Library("ARKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class ARGeoTrackingStatus extends NSObject implements NSCopying, NSSecureCoding {
    static {
        NatJ.register();
    }

    @Generated
    protected ARGeoTrackingStatus(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    /**
     * The accuracy of geo tracking.
     */
    @Generated
    @Selector("accuracy")
    @NInt
    public native long accuracy();

    @Generated
    @Owned
    @Selector("alloc")
    public static native ARGeoTrackingStatus alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native ARGeoTrackingStatus allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Owned
    @Selector("copyWithZone:")
    @MappedReturn(ObjCObjectMapper.class)
    public native Object copyWithZone(VoidPtr zone);

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("encodeWithCoder:")
    public native void encodeWithCoder(NSCoder coder);

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("init")
    public native ARGeoTrackingStatus init();

    @Generated
    @Selector("initWithCoder:")
    public native ARGeoTrackingStatus initWithCoder(NSCoder coder);

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native ARGeoTrackingStatus new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    /**
     * The state of geo tracking.
     */
    @Generated
    @Selector("state")
    @NInt
    public native long state();

    /**
     * Reason for geo tracking state.
     */
    @Generated
    @Selector("stateReason")
    @NInt
    public native long stateReason();

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("supportsSecureCoding")
    public static native boolean supportsSecureCoding();

    @Generated
    @ProtocolClassMethod("supportsSecureCoding")
    public boolean _supportsSecureCoding() {
        return supportsSecureCoding();
    }

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();
}


text:
inesa
=====

Cotizador online Queretaro


text:
import argparse
import csv
from dateutil.parser import parse
import re
import sys

def entries(input):
    date = None
    entry = ""
    for line in input:
        if not line.strip():
            continue
        if line.startswith("#"):
            if date is not None:
                yield date, entry
                entry = ""
            try:
                date = parse(line[1:]).date()
            except ValueError:
                print(f"Failed to parse date: {line}", file=sys.stderr)
                sys.exit(1)
        else:
            entry += line
    if date is not None:
        yield date, entry

def write_counts(output, input, regex):
    print("date,count", file=output)
    for date, entry in entries(input):
        count = len(re.findall(regex, entry))
        print(f"{date},{count}", file=output)

def parse_args():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("input", metavar="F", help="Journal input file")
    parser.add_argument(
        "-o", "--output", default="wordcount.csv", help="Output CSV file"
    )
    parser.add_argument(
        "-r", "--regex", default=r"\b\w+\b", help="Count occurrences of regex per day"
    )
    return parser.parse_args()

def main():
    args = parse_args()
    regex = re.compile(args.regex, re.IGNORECASE)
    print(f"Using regex: {regex}")
    with open(args.input) as input_file, open(args.output, "w") as output_file:
        write_counts(output_file, input_file, regex)

if __name__ == "__main__":
    main()


text:
#include "comms-precomp.h"	// Precompiled headers
//
#include <mrpt/comms/nodelets.h>

using namespace mrpt::comms;

// ------- Subscriber --------------
Subscriber::Subscriber(
	std::function<void(const std::any&)>&& func,
	std::function<void()>&& cleanup)
	: m_func(std::move(func)), m_cleanup(std::move(cleanup))
{
}

Subscriber::~Subscriber() { m_cleanup(); }
Subscriber::Ptr Subscriber::create(
	std::function<void(const std::any&)>&& func,
	std::function<void()>&& cleanup)
{
	return Ptr(new Subscriber(std::move(func), std::move(cleanup)));
}

void Subscriber::pub(const std::any& a) { m_func(a); }
// ------- Topic --------------
Topic::Topic(std::function<void()>&& cleanup) : m_cleanup(std::move(cleanup)) {}
Topic::~Topic() { m_cleanup(); }
void Topic::publish(const std::any& any)
{
	std::lock_guard<std::mutex> lock(m_mutex);
	for (auto& sub : m_subs)
	{
		sub.lock()->pub(any);
	}
}

void Topic::cleanupSubscriber(std::list<std::weak_ptr<Subscriber>>::iterator it)
{
	std::lock_guard<std::mutex> lock(m_mutex);
	m_subs.erase(it);
}

// -------------- TopicDirectory ---------------------
TopicDirectory::TopicDirectory() = default;

void TopicDirectory::cleanupTopic(const std::string& key)
{
	std::lock_guard<std::mutex> lock(m_mutex);
	m_mapService.erase(m_mapService.find(key));
}

TopicDirectory::Ptr TopicDirectory::create() { return Ptr(new TopicDirectory); }


text:
static NSString *const kFBSDKAccessTokenUserDefaultsKey = @"com.facebook.sdk.v4.FBSDKAccessTokenInformationKey";
static NSString *const kFBSDKAccessTokenKeychainKey = @"com.facebook.sdk.v4.FBSDKAccessTokenInformationKeychainKey";
static NSString *const kFBSDKAccessTokenUUIDKey = @"tokenUUID";
static NSString *const kFBSDKAccessTokenEncodedKey = @"tokenEncoded";

@implementation FBSDKAccessTokenCache
{
  FBSDKKeychainStore *_keychainStore;
}

- (instancetype)init
{
  if ((self = [super init])) {
    NSString *keyChainServiceIdentifier = [NSString stringWithFormat:@"com.facebook.sdk.tokencache.%@", [NSBundle mainBundle].bundleIdentifier];
    _keychainStore = [[FBSDKKeychainStore alloc] initWithService:keyChainServiceIdentifier accessGroup:nil];
  }
  return self;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (FBSDKAccessToken *)accessToken
{
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  NSString *uuid = [defaults objectForKey:kFBSDKAccessTokenUserDefaultsKey];

  NSDictionary<NSString *, id> *dict = [_keychainStore dictionaryForKey:kFBSDKAccessTokenKeychainKey];
  if ([dict[kFBSDKAccessTokenUUIDKey] isKindOfClass:[NSString class]]) {
    // there is a bug while running on simulator that the uuid stored in dict can be NSData,
    // do a type check to make sure it is NSString
    if ([dict[kFBSDKAccessTokenUUIDKey] isEqualToString:uuid]) {
      id tokenData = dict[kFBSDKAccessTokenEncodedKey];
      if ([tokenData isKindOfClass:[NSData class]]) {
        return [NSKeyedUnarchiver unarchiveObjectWithData:tokenData];
      }
    }
  }
  // if the uuid doesn't match (including if there is no uuid in defaults which means uninstalled case)
  // clear the keychain and return nil.
  [self clearCache];
  return nil;
}

- (void)setAccessToken:(FBSDKAccessToken *)token
{
  if (!token) {
    [self clearCache];
    return;
  }
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  NSString *uuid = [defaults objectForKey:kFBSDKAccessTokenUserDefaultsKey];
  if (!uuid) {
    uuid = [NSUUID UUID].UUIDString;
    [defaults setObject:uuid forKey:kFBSDKAccessTokenUserDefaultsKey];
    [defaults synchronize];
  }
  NSData *tokenData = [NSKeyedArchiver archivedDataWithRootObject:token];
  NSDictionary<NSString *, id> *dict = @{
                                         kFBSDKAccessTokenUUIDKey : uuid,
                                         kFBSDKAccessTokenEncodedKey : tokenData
                                         };

  [_keychainStore setDictionary:dict
                         forKey:kFBSDKAccessTokenKeychainKey
                  accessibility:[FBSDKDynamicFrameworkLoader loadkSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]];
}
#pragma clang diagnostic pop

- (void)clearCache
{
  [_keychainStore setDictionary:nil
                         forKey:kFBSDKAccessTokenKeychainKey
                  accessibility:NULL];
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  [defaults removeObjectForKey:kFBSDKAccessTokenUserDefaultsKey];
  [defaults synchronize];
}
@end


text:
//===========================================
//  Lumina-DE source code
//  Copyright (c) 2017-2018, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "NativeWindowObject.h"
#include <QQmlEngine>
#include <QDebug>
#include <QBuffer>

// == QML Type Registration ==
void NativeWindowObject::RegisterType(){
  static bool done = false;
  if(done){ return; }
  done=true;
  qmlRegisterType<NativeWindowObject>("Lumina.Backend.NativeWindowObject",2,0, "NativeWindowObject");
}

// === PUBLIC ===
NativeWindowObject::NativeWindowObject(WId id) : QObject(){
  winid = id;
  frameid = 0;
  dmgID = dmg = 0;
  geomTimer = new QTimer(this);
    geomTimer->setSingleShot(true);
    geomTimer->setInterval(50); //1/20 second
  connect(geomTimer, SIGNAL(timeout()), this, SLOT(sendNewGeom()) );
  qRegisterMetaType<WId>("WId");
}

NativeWindowObject::~NativeWindowObject(){
  hash.clear();
}

void NativeWindowObject::addFrameWinID(WId fid){
  frameid = fid;
}

void NativeWindowObject::addDamageID(unsigned int dmg){
  dmgID = dmg;
}

bool NativeWindowObject::isRelatedTo(WId tmp){
  return (relatedTo.contains(tmp) || winid == tmp || frameid == tmp);
}

WId NativeWindowObject::id(){
  return winid;
}

WId NativeWindowObject::frameId(){
  return frameid;
}

unsigned int NativeWindowObject::damageId(){
  return dmgID;
}

QVariant NativeWindowObject::property(NativeWindowObject::Property prop){
  if(hash.contains(prop)){ return hash.value(prop); }
  else if(prop == NativeWindowObject::RelatedWindows){ return QVariant::fromValue(relatedTo); }
  return QVariant(); //null variant
}

void NativeWindowObject::setProperty(NativeWindowObject::Property prop, QVariant val, bool force){
  if(prop == NativeWindowObject::RelatedWindows){ relatedTo = val.value< QList<WId> >(); }
  else if(prop == NativeWindowObject::None || (!force && hash.value(prop)==val)){ return; }
  else if(prop == NativeWindowObject::WinImage){
      //special case - This should never be actually set in the property hash
      //  it is loaded dynamically by the QMLImageProvider instead (prevent flickering/caching image)
  } else{ hash.insert(prop, val); }
  emitSinglePropChanged(prop);
  emit PropertiesChanged(QList<NativeWindowObject::Property>() << prop, QList<QVariant>() << val);
}

void NativeWindowObject::setProperties(QList<NativeWindowObject::Property> props, QList<QVariant> vals, bool force){
  for(int i=0; i<props.length(); i++){
    if(i>=vals.length()){ props.removeAt(i); i--; continue; } //no corresponding value for this property
    if(props[i] == NativeWindowObject::None || (!force && (hash.value(props[i]) == vals[i])) ){
      props.removeAt(i); vals.removeAt(i); i--; continue; //Invalid property or identical value
    }else if(props[i] == NativeWindowObject::WinImage){
      //special case - This should never be actually set in the property hash
      //  it is loaded dynamically by the QMLImageProvider instead (prevent flickering/caching image)
    }else{
      hash.insert(props[i], vals[i]);
    }
    emitSinglePropChanged(props[i]);
  }
  emit PropertiesChanged(props, vals);
}

void NativeWindowObject::requestProperty(NativeWindowObject::Property prop, QVariant val, bool force){
  if(prop == NativeWindowObject::None || prop == NativeWindowObject::RelatedWindows || (!force && hash.value(prop)==val) ){ return; }
  emit RequestPropertiesChange(winid, QList<NativeWindowObject::Property>() << prop, QList<QVariant>() << val);
}

void NativeWindowObject::requestProperties(QList<NativeWindowObject::Property> props, QList<QVariant> vals, bool force){
  //Verify/adjust inputs as needed
  for(int i=0; i<props.length(); i++){
    if(i>=vals.length()){ props.removeAt(i); i--; continue; } //no corresponding value for this property
    if(props[i] == NativeWindowObject::None || props[i] == NativeWindowObject::RelatedWindows || (!force && hash.value(props[i])==vals[i]) ){ props.removeAt(i); vals.removeAt(i); i--; continue; } //Invalid property or identical value
    /*if( (props[i] == NativeWindowObject::Visible || props[i] == NativeWindowObject::Active) && frameid !=0){
      //These particular properties needs to change the frame - not the window itself
      emit RequestPropertiesChange(frameid, QList<NativeWindowObject::Property>() << props[i], QList<QVariant>() << vals[i]);
      props.removeAt(i); vals.removeAt(i); i--;
    }*/
  }
  emit RequestPropertiesChange(winid, props, vals);
}

QRect NativeWindowObject::geometry(){
  //Calculate the "full" geometry of the window + frame (if any)
  //Check that the size is between the min/max limitations
  QSize size = hash.value(NativeWindowObject::Size).toSize();
  QSize min = hash.value(NativeWindowObject::MinSize).toSize();
  QSize max = hash.value(NativeWindowObject::MaxSize).toSize();
  if(min.isValid() && min.width() > size.width() ){ size.setWidth(min.width()); }
  if(min.isValid() && min.height() > size.height()){ size.setHeight(min.height()); }
  if(max.isValid() && max.width() < size.width()  && max.width()>min.width()){ size.setWidth(max.width()); }
  if(max.isValid() && max.height() < size.height()  && max.height()>min.height()){ size.setHeight(max.height()); }
  //Assemble the full geometry
  QRect geom( hash.value(NativeWindowObject::GlobalPos).toPoint(), size );
  //Now adjust the window geom by the frame margins
  QList<int> frame = hash.value(NativeWindowObject::FrameExtents).value< QList<int> >(); //Left,Right,Top,Bottom
  //qDebug() << "Calculate Geometry:" << geom << frame;
  if(frame.length()==4){
    geom = geom.adjusted( -frame[0], -frame[2], frame[1], frame[3] );
  }
  //qDebug() << " - Total:" << geom;
  return geom;
}

void NativeWindowObject::setGeometryNow(QRect geom){
  updateGeometry(geom.x(), geom.y(), geom.width(), geom.height(), true);
}

// QML ACCESS FUNCTIONS (shortcuts for particular properties in a format QML can use)
QString NativeWindowObject::winImage(){
  //Need to alternate something on the end to ensure that QML knows to fetch the new image (non-cached only)
  if(dmg==0){ dmg = 1; }
  else{ dmg = 0; }
  return "image://native_window/image:"+QString::number(winid)+":"+QString::number(dmg);
}

QString NativeWindowObject::name(){
  return this->property(NativeWindowObject::Name).toString();
}

QString NativeWindowObject::title(){
  return this->property(NativeWindowObject::Title).toString();
}

QString NativeWindowObject::shortTitle(){
  QString tmp = this->property(NativeWindowObject::ShortTitle).toString();
  if(tmp.isEmpty()){ tmp = title(); }
  if(tmp.isEmpty()){ tmp = name(); }
  return tmp;
}

QString NativeWindowObject::icon(){
  if(icodmg==0){ icodmg=1; }
  else{ icodmg = 0; }
  qDebug() << "Window Icon:" << icodmg << this->property(NativeWindowObject::Icon).value<QIcon>().availableSizes();
  return "image://native_window/icon:"+QString::number(winid)+":"+QString::number(icodmg);
}

//QML Button states
bool NativeWindowObject::showCloseButton(){
  QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
  QList<NativeWindowObject::Type> badtypes;
  badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
	<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
	<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
  for(int i=0; i<types.length(); i++){
    if(badtypes.contains(types[i])){ return false; }
  }
  return true;
}

bool NativeWindowObject::showMaxButton(){
  QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
  QList<NativeWindowObject::Type> badtypes;
  badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
	<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
	<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
  for(int i=0; i<types.length(); i++){
    if(badtypes.contains(types[i])){ return false; }
  }
  return true;
}

bool NativeWindowObject::showMinButton(){
  QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
  QList<NativeWindowObject::Type> badtypes;
  badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
	<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
	<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND << NativeWindowObject::T_DIALOG;
  for(int i=0; i<types.length(); i++){
    if(badtypes.contains(types[i])){ return false; }
  }
  return true;
}

bool NativeWindowObject::showTitlebar(){
  QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
  QList<NativeWindowObject::Type> badtypes;
  badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
	<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
	<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
  for(int i=0; i<types.length(); i++){
    if(badtypes.contains(types[i])){ return false; }
  }
  return true;
}

bool NativeWindowObject::showGenericButton(){
  QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
  QList<NativeWindowObject::Type> badtypes;
  badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
	<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
	<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
  for(int i=0; i<types.length(); i++){
    if(badtypes.contains(types[i])){ return false; }
  }
  return true;
}

bool NativeWindowObject::showWindowFrame(){
  QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
  QList<NativeWindowObject::Type> badtypes;
  badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
	<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
	<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
  for(int i=0; i<types.length(); i++){
    if(badtypes.contains(types[i])){ return false; }
  }
  return true;
}

//QML Window States
bool NativeWindowObject::isSticky(){
  return (this->property(NativeWindowObject::Workspace).toInt()<0 || this->property(NativeWindowObject::States).value<QList<NativeWindowObject::State> >().contains(NativeWindowObject::S_STICKY) );
}

bool NativeWindowObject::isVisible(){
  return (this->property(NativeWindowObject::Visible).toBool() );
}

int NativeWindowObject::workspace(){
  return this->property(NativeWindowObject::Workspace).toInt();
}

//QML Geometry reporting
QRect NativeWindowObject::frameGeometry(){
  return geometry();
}

QRect NativeWindowObject::imageGeometry(){
  QRect geom( this->property(NativeWindowObject::GlobalPos).toPoint(), this->property(NativeWindowObject::Size).toSize() );
  return geom;
}

void NativeWindowObject::updateGeometry(int x, int y, int width, int height, bool now){
  // Full frame+window geometry - go ahead and pull it apart and only update the interior window geom
  QList<int> fgeom = this->property(NativeWindowObject::FrameExtents).value<QList<int> >();
  if(fgeom.isEmpty()){ fgeom << 0<<0<<0<<0; } //just in case (left/right/top/bottom)
  QPoint pos(x+fgeom[0], y+fgeom[2]);
  QSize sz(width-fgeom[0]-fgeom[1], height-fgeom[2]-fgeom[3]);
  newgeom = QRect(pos, sz);
  lastgeom = QRect(x,y,width,height); //save this for later
  if(!now){
    //qDebug() << "Update Geometry:" << fgeom << QRect(x,y,width,height) << pos << sz;
    //requestProperties(QList<NativeWindowObject::Property>() << NativeWindowObject::GlobalPos << NativeWindowObject::Size, QList<QVariant>() << pos << sz);
    if(!geomTimer->isActive()){ QTimer::singleShot(0,geomTimer, SLOT(start())); }
  }else{
   sendNewGeom();
  }
}

// ==== PUBLIC SLOTS ===
void NativeWindowObject::toggleVisibility(){
  setProperty(NativeWindowObject::Visible, !property(NativeWindowObject::Visible).toBool() );
}

void NativeWindowObject::toggleMaximize(){
  //Find the screen containing this window (center of window)
  QRect curgeom = frameGeometry();
  QPoint ctr = curgeom.center();
  QList<QScreen*> scrns = QApplication::screens();
  QRect max;
  for(int i=0; i<scrns.length(); i++){
    if(scrns[i]->geometry().contains(ctr)){
      max = scrns[i]->availableGeometry();
      break;
    }
  }
  //Now compare the current geometry to the screen geometry
  qDebug() << "Maximize Toggle:" << curgeom << max;
  if(curgeom!=max){
    qDebug() << " - maximize";
    setGeometryNow(max); //will set newgeom to max
    lastgeom = curgeom; //save this for later
  }else{
    qDebug() << " - restore" << lastgeom;
    //Already maximized, look at the old geometry and figure out how to restore it
    if(lastgeom.isNull() || lastgeom == max){
      qDebug() << " -- Reset lastgeom to half-screen size";
      //no old info available - center the window at half maximum size
      lastgeom = QRect(max.x()-max.width()/2, max.y()-max.height()/2, max.width()/2, max.height()/2);
    }
    setGeometryNow(lastgeom);
  }
  qDebug() << "After toggle:" << lastgeom;
  //emit geomChanged();
}

void NativeWindowObject::requestClose(){
  emit RequestClose(winid);
}

void NativeWindowObject::requestKill(){
  emit RequestKill(winid);
}

void NativeWindowObject::requestPing(){
  emit RequestPing(winid);
}

void NativeWindowObject::requestActivate(){
  requestProperty(NativeWindowObject::Active, true);
}

// ==== PRIVATE ====
void NativeWindowObject::emitSinglePropChanged(NativeWindowObject::Property prop){
  //Simple switch to emit the QML-usable signals as properties are changed
  switch(prop){
	case NativeWindowObject::Name:
		emit nameChanged(); break;
	case NativeWindowObject::Title:
		emit titleChanged();
		if(this->property(NativeWindowObject::ShortTitle).toString().isEmpty()){ emit shortTitleChanged(); }
		break;
	case NativeWindowObject::ShortTitle:
		emit shortTitleChanged(); break;
	case NativeWindowObject::Icon:
		emit iconChanged(); break;
	case NativeWindowObject::Workspace:
	case NativeWindowObject::States:
		emit stickyChanged(); break;
	case NativeWindowObject::WinImage:
		emit winImageChanged(); break;
	case NativeWindowObject::WinTypes:
		emit winTypeChanged(); break;
	case NativeWindowObject::Visible:
		emit visibilityChanged(); break;
	default:
		break; //do nothing otherwise
  }
}

void NativeWindowObject::sendNewGeom(){
  QList<NativeWindowObject::Property> props; props << NativeWindowObject::GlobalPos << NativeWindowObject::Size;
  QList<QVariant> vals; vals << newgeom.topLeft() << newgeom.size();
  requestProperties(props, vals);
  setProperties(props,vals);
  emit VerifyNewGeometry(winid);
}


text:
Fantastico features
===================

.. toctree::
   :maxdepth: 2

   exceptions
   request_response
   routing_engine
   mvc
   cors
   roa
   oauth2
   sdk
   component_model
   component_reusage
   components_builtin


text:
#include "Arduino.h"
#include "Constants.h"
#include <ArduinoJson.h>
#include <HardwareSerial.h>
#include <FS.h>

extern "C" {
  #include <user_interface.h>
  #include <umm_malloc/umm_malloc.h>
}

/*
 * Configuration
 */
#define DEBUG
#define BROWSER_EVENTS

#ifdef DEBUG
void debug_plain(const char *msg);
void debug_message(const char *module, const char *format, ...);

//browser_event("debug", __VA_ARGS__);

#define DEBUG_PLAIN(msg) debug_plain(msg)
#define DEBUG_MSG(module, format, ...) debug_message(module, format, ##__VA_ARGS__ )
#else
#define DEBUG_PLAIN(msg)
#define DEBUG_MSG(...) if (ESP.getFreeHeap() < g_minFreeHeap) { g_minFreeHeap = ESP.getFreeHeap(); }
#endif

/*
 * Plugins
 */
#define OTA_SERVER
#define CAPTIVE_PORTAL
#define PLUGIN_ONEWIRE
#define PLUGIN_DHT
#define PLUGIN_ANALOG
#define PLUGIN_WIFI

// #define SPIFFS_EDITOR

extern bool loadConfig();
extern bool saveConfig();
extern MD5Builder getHashBuilder();
extern String getHash();


text:
<!doctype html>

      <meta charset="utf-8">
      <title>2013-FR-10b</title>
    <link class="module" rel="stylesheet" href="../../../_common/modules/pemFioi/taskStyles-0.1.css" id="http://www.france-ioi.org/modules/pemFioi/taskStyles-0.1.css">

      <link rel="stylesheet" type="text/css" href="../2013-FR-10a/style.css">

Chercher-remplacer

      Castor a récupéré un fichier constitué de 12 lignes ayant toutes le même format. Il a besoin de modifier le format de ces données, exactement comme décrit ci-dessous.

      Avant :

      <textarea id='source' style='height:80px' readonly cols='30' class='pattern'></textarea>

      Après : (attention aux espaces)

      <textarea id='dest' style='height:80px' readonly cols='30' class='pattern'></textarea>

      Pour convertir ses données efficacement, Castor aimerait utiliser l'outil « chercher-remplacer »
      qui permet de remplacer, partout dans le texte, une séquence de caractères par une autre.

Pouvez-vous montrer à Castor comment s'y prendre en moins de 11 étapes ?

      Outil :

               Chercher :
               <input type='text' id='search' class='pattern' autocapitalize='off'>

               Remplacer par :
               <input type='text' id='replace' class='pattern' autocapitalize='off'>

            <input type='button' id='replace_all' value='Remplacer tout' style='padding: 5px; margin-bottom:5px; font-weight: bold'>

      État courant du fichier :

<textarea id='current' style='height:80px' readonly cols='30' class='pattern'></textarea>

        <input type='button' id='cancel' value='Annuler une étape'>

Solution

On peut effectuer les 3 remplacements décrits ci-dessous :

         Chercher
         Remplacer par
         Résultat

         mix(rouge,bleu)=violet

         mix(
         rien
         rouge,bleu)=violet

         ,(
          +
         rouge + bleu)=violet

         )=
          =
         rouge + bleu = violet

La principale difficulté provient du fait que l'on veut remplacer
     une virgule par un deux-points, et un deux-points par une virgule.
     Plusieurs méthodes sont possibles pour contourner ce problème.

Une première méthode consiste à utiliser
     un caractère intermédaire, par exemple #,
     pendant les remplacements, comme décrit ci-dessous :

         Chercher
         Remplacer par
         Résultat

         ((42-3)+5),8:5,72

         ((
         (
         (42-3)+5),8:5,72

         )+
         +
         (42-3+5),8:5,72

         :
         #
         (42-3+5),8#5,72

         ),
         ):
         (42-3+5):8#5,72

         ,
         :
         (42-3+5):8#5:72

         #
         ,
         (42-3+5):8,5::72

Une seconde méthode permet de s'en sortir sans introduire un
     caractère intermédiaire. Il faut pour cela remplacer la
     virgule par une double virgule avant de remplacer la virgule
     par un deux-points. Voici comment faire :

         Chercher
         Remplacer par
         Résultat

         ((42-3)+5),8:5,72

         ((
         (
         (42-3)+5),8:5,72

         )+
         +
         (42-3+5),8:5,72

         ,
         ,,
         (42-3+5),,8:5,,72

         :
         ,
         (42-3+5),,8,5,,72

         ),,
         ):
         (42-3+5):8,5,,72

         ,,
         ::
         (42-3+5):8,5::72

C'est de l'informatique !

      Lorsqu'on manipule des textes sous forme de fichier, il est très pratique
      de pouvoir chercher toutes les occurrences (les apparitions)
      d'un mot dans ce texte. De même, il est très pratique de pouvoir remplacer
      toutes ces occurrences d'un mot par un autre mot.

      Dans ce sujet, on s'intéressait à remplacer tous les mots qui apparaissent
      exactement sous une forme donnée. Dans d'autres problèmes de la vie réelle,
      on s'intéresse à savoir si une forme approchée d'un mot donné apparaît
      dans un texte.
      Par exemple, cela sert en biologie : on dispose
      d'une séquence d'ADN, c'est-à-dire un très long texte formé uniquement
      des lettres A, G, C et T, et on souhaite détecter si cette séquence
      contient une version mutée d'un gène donné.

Le gène est décrit par
      une relativement courte séquence de lettres, mais certaines de ces
      lettres peuvent avoir été modifiées suite à des mutations.
      Vu que les séquences d'ADN contiennent des milliards de symboles,
      il est important de disposer d'algorithmes très efficaces de recherche
      de motifs.


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cereus mojavensis Engelm. & J.M.Bigelow

### Remarks
null


text:
namespace mojo {
class ApplicationDelegate;
}

namespace device {

// Public factory for creating new instances of the devices app.
class DevicesAppFactory {
 public:
  // Creates a DevicesApp delegate which can be used to launch a new instance
  // of the devices app on a mojo application runner. The caller owns the
  // delegate.
  static scoped_ptr<mojo::ApplicationDelegate> CreateApp();
};

}  // namespace device

#endif  // DEVICE_DEVICES_APP_PUBLIC_CPP_DEVICES_APP_FACTORY_H_


text:
layout: markdown_page
title: "GitLab General Questions"
---
This short quiz is about general aspects related to GitLab. They are open questions which will allow people to prepare and retest without losing accuracy and will make sharing easier.

1. What is the difference between GitLab CE and EE?

1. What is the meaning of "on-premises software"?

1. What does "open source" mean?

1. What is the difference between GitLab and GitLab.com?

1. Which are the services that GitLab offers?

1. Can explain what a SaaS software is in your own words?

1. Why does dev.GitLab.org exist and what is the difference between it and GitLab.com?

1. What is a repository?

1. What is Git?

1. What is Continuous integration?

1. What is the difference between a GitLab user and a GitLab customer?

1. Why should we refer to 'the rest of the GitLab community' instead of 'the GitLab community'?


text:
using FB2Library.Elements;
using System;
using ConverterContracts.ConversionElementsStyles;
using XHTMLClassLibrary.BaseElements;
using XHTMLClassLibrary.BaseElements.InlineElements;

namespace FB2EPubConverter.ElementConvertersV3
{
    internal class InlineImageConverterParamsV3
    {
        public ConverterOptionsV3 Settings { get; set; }
    }

    internal class InlineImageConverterV3 : BaseElementConverterV3
    {
        /// <summary>
        /// Converts FB2 inline image
        /// </summary>
        /// <returns></returns>
        public IHTMLItem Convert(InlineImageItem inlineImageItem, InlineImageConverterParamsV3 inlineImageConverterParams)
        {
            if (inlineImageItem == null)
            {
                throw new ArgumentNullException("inlineImageItem");
            }
            var img = new Image(HTMLElementType.HTML5);
            img.Alt.Value = inlineImageItem.AltText ?? string.Empty;

            img.Source.Value = inlineImageConverterParams.Settings.ReferencesManager.AddImageRefferenced(inlineImageItem, img);

            SetClassType(img, ElementStylesV3.InlineImage);
            return img;
        }
    }
}


text:
/*jslint node: true */
/*global module, require*/
'use strict';

var ExecutionError = require('../error/execution');

module.exports = function fail(name, value, callback) {
  if (typeof value === 'function') {
    callback = value;
    value = undefined;
  }

  if (!this.hasBegun(name)) {
    return callback && callback(new ExecutionError(
      'An item with this name has not yet started.'));
  }
  if (this.hasFinished(name)) {
    return callback && callback(new ExecutionError(
      'An item with this name has already completed.'));
  }
  this.state.completed[name] = true;

  this.state.completed[name] = {
    error: value
  };

  return callback && callback(null);
};


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class general extends CI_Model
{

	function __construct()
	{
		parent::__construct();
		$this->load->model('/bo/bonos/calculador_bono');
		$this->load->model('/bo/bonos/afiliado');

	}

	function IsActivedPago($id){
		$q = $this->db->query('select estatus from user_profiles where user_id = '.$id);
		$estado = $q->result();

		if($estado[0]->estatus == 'ACT'){
			return true;
		}else{
			if($this->VerificarCompraPaquete($id)){
				$this->actualizarEstadoAfiliado($id);
				return true;
			}else{
				return false;
			}
		}
	}

	function actualizarEstadoAfiliado($id){
		$q = $this->db->query("UPDATE user_profiles SET estatus = 'ACT' WHERE user_id = ".$id);
	}

	function VerificarCompraPaquete($id){
		$q = $this->db->query("SELECT m.id FROM cross_venta_mercancia cvm, venta v, mercancia m
		where v.id_estatus = 2 and cvm.id_venta = v.id_venta and cvm.id_mercancia = m.id and m.id_tipo_mercancia = 4 and v.id_user = ".$id);

		$mercnacias_id = $q->result();

		if(isset($mercnacias_id[0]->id)){
			return true;
		}else{
			return false;
		}
	}

	function isAValidUser($id,$modulo){

		$q=$this->db->query('SELECT cu.id_tipo_usuario as tipoId
							FROM users u , user_profiles up ,cat_tipo_usuario cu
							where(u.id=up.user_id)
							and (up.id_tipo_usuario=cu.id_tipo_usuario)
							and(u.id='.$id.')');
		$tipo=$q->result();

		$idTipoUsuario=$tipo[0]->tipoId;

		$perfiles = array(

				"OV" => $this->IsActivedPago($id),
				"comercial" => ($idTipoUsuario==4) ? true : false,
				"soporte" => ($idTipoUsuario==3) ? true : false,
				"logistica" => ($idTipoUsuario==5) ? true : false,
				"oficina" => ($idTipoUsuario==6) ? true : false,
				"administracion" => ($idTipoUsuario==7) ? true : false,
				"cedi" => ($idTipoUsuario==8) ? true : false,
				"almacen" => ($idTipoUsuario==9) ? true : false,

		);

		return ($idTipoUsuario==1) ? true :$perfiles[$modulo];
	}

	function isActived($id){

		if($id==2)
			return 0;

		return $this->validarMembresias($id);
		#return $this->isActivedAfiliado($id) ? 0 : 3;

	}

	function isActivedAfiliado($id_usuario,$red = 1){

		#$puntos = $this->getEmpresa ("puntos_personales");

		$productos=$this->getComprasUnidades($id_usuario,1);
		$lider=$this->getComprasUnidades($id_usuario,5,8);
		$intermedia=$this->getComprasUnidades($id_usuario,5,7);

		#log_message('DEV',"unidades : $productos + $intermedia o $lider");

		$Pasa = (($productos+$intermedia)>1 || $lider>0) ? true : false;

		return $Pasa;
	}

	private function getComprasUnidades($id_usuario,$tipo = 0,$mercancia = 0,$red = 1){

		$where = "";$fecha = date('Y-m');

		if($tipo!=0){
			$in = (gettype($tipo)=="array") ? implode(",", $tipo) : $tipo;
			$where.=" AND i.id_tipo_mercancia in ($in)";
		}

		if($mercancia!=0){
			$in = (gettype($mercancia)=="array") ? implode(",", $mercancia) : $mercancia;
			$where.=" AND i.id in ($in)";
		}

		$query = "SELECT
						sum(cvm.cantidad) unidades
					FROM
						venta v,
						cross_venta_mercancia cvm,
						items i
					WHERE
						i.id = cvm.id_mercancia
						AND cvm.id_venta = v.id_venta
						AND v.id_user = $id_usuario
						AND i.red = $red
						$where
						AND v.id_estatus = 'ACT'
						AND date_format(v.fecha,'%Y-%m') = '$fecha'";

		$q = $this->db->query($query);
		$q =$q->result();

		if(!$q)
			return 0;

		return intval($q[0]->unidades);

	}

	function isDuplicado($id_usuario,$red=1){

		$query = "SELECT * FROM afiliar WHERE id_afiliado = $id_usuario AND id_red = $red AND duplicado = 'ACT'";

		$q = $this->db->query($query);
		$q =$q->result();

		return $q ? 2 : 1;

	}

	function isActivedAfiliacionesPuntosPersonales($id_afiliado,$fecha){
	$cualquiera="0";

	$numeroAfiliadosDirectos=$this->getAfiliadosDirectos($id_afiliado);
	$afiliadosParaEstarActivo=$this->getAfiliadosParaEstarActivo();

	if($afiliadosParaEstarActivo>$numeroAfiliadosDirectos)
		return false;

	$fechaInicio=$this->calculador_bono->getInicioMes($fecha);
	$fechaFin=$this->calculador_bono->getFinMes($fecha);

	$puntosParaEstarActivo=$this->getPuntosParaEstarActivo();
	$puntosComisionablesMes=0;

	$q=$this->db->query('select id from tipo_red');
	$redes= $q->result();

	foreach ($redes as $red){
		$puntos=$this->afiliado->getPuntosTotalesPersonalesIntervalosDeTiempo($id_afiliado,$red->id,$cualquiera,$cualquiera,$fechaInicio,$fechaFin);
		$puntosComisionablesMes=$puntosComisionablesMes+$puntos;

	}

	if($puntosParaEstarActivo>$puntosComisionablesMes)
		return false;

	return true;
	}

	private function getAfiliadosDirectos($id_afiliado){
		$q=$this->db->query('SELECT count(*) as directos FROM users u,afiliar a
		where u.id=a.id_afiliado and a.directo = '.$id_afiliado);
		$numeroAfiliados=$q->result();

		if($numeroAfiliados[0]->directos==null)
			return 0;

		return $numeroAfiliados[0]->directos;

	}

	private function getAfiliadosParaEstarActivo(){
		$q=$this->db->query('SELECT afiliados_directos as directos FROM empresa_multinivel');
		$afiliadosDirectos=$q->result();

		if($afiliadosDirectos[0]->directos==null)
			return 0;

		return $afiliadosDirectos[0]->directos;
	}

	private function getPuntosParaEstarActivo(){
		$q=$this->db->query('SELECT puntos_personales as puntos FROM empresa_multinivel');
		$afiliadosDirectos=$q->result();

		if($afiliadosDirectos[0]->puntos==null)
			return 0;

		return $afiliadosDirectos[0]->puntos;
	}

	private function validarMembresias($id){
		$membresia=1;

		if($this->compraObligatoria ($membresia)&&$this->hayTipoDeMercancia ($membresia)){
			if($this->compraDeUsuarioEstaActiva($membresia,$id)){
				// validar Paquetes
				return $this->validarPaqueteInscripcion($id);
			}
			else{
				//Mostrar Membresias
				return 1;
			}
		}else {
			//validarPaquetes

			return $this->validarPaqueteInscripcion($id);

		}
	}

	private function validarPaqueteInscripcion($id){
		$paqueteDeInscripcion=2;

		if($this->compraObligatoria ($paqueteDeInscripcion)&&$this->hayTipoDeMercancia ($paqueteDeInscripcion)){
			if($this->compraDeUsuarioEstaActiva($paqueteDeInscripcion,$id)){
					// validar Items
				return $this->validarItems($id);
			}
			else{
				//Mostrar Paquetes
				return 2;
			}
		}else {
			// validar Items
			return $this->validarItems($id);
		}
	}

	private function validarItems($id){
		$item=3;

		if($this->compraObligatoria ($item)&&$this->hayTipoDeMercancia ($item)){
			if($this->compraDeUsuarioEstaActiva($item,$id)){
				// Acceso
				return 0;
			}
			else{
				//Mostrar Item
				return 3;
			}
		}else {
			// Acceso
			return 0;
		}
	}

	private function compraObligatoria($id_tipo_mercancia) {

		if($id_tipo_mercancia == 1){
			$q = $this->db->query("SELECT membresia as estado FROM empresa_multinivel;");
		}elseif ($id_tipo_mercancia == 2){
			$q = $this->db->query("SELECT paquete as estado FROM empresa_multinivel;");
		}elseif($id_tipo_mercancia == 3) {
			$q = $this->db->query("SELECT item as estado FROM empresa_multinivel;");
		}else{
			return false;
		}
		$estado=$q->result();

		if($estado[0]->estado=='ACT')
			return true;

		return false;

	}

	private function hayTipoDeMercancia($id_tipo_mercancia) {

		if($id_tipo_mercancia == 1){
			$q = $this->db->query("SELECT * FROM mercancia where id_tipo_mercancia=5");
		}elseif ($id_tipo_mercancia == 2){
			$q = $this->db->query("SELECT * FROM mercancia where id_tipo_mercancia=4");
		}elseif($id_tipo_mercancia == 3) {
			$q = $this->db->query("SELECT * FROM mercancia where id_tipo_mercancia=1 or id_tipo_mercancia=2 or id_tipo_mercancia=3");
		}else{
			return false;
		}

		$mercancia=$q->result();

		if($mercancia)
			return true;

		return false;

	}

	private function compraDeUsuarioEstaActiva($id_tipo_mercancia,$id) {

		if($id_tipo_mercancia == 1){
			$q = $this->db->query("SELECT v.id_venta,v.fecha,me.caducidad,DATEDIFF(now(),v.fecha)as dias_activacion FROM venta v,cross_venta_mercancia cvm,mercancia m,membresia me
									where v.id_estatus='ACT'
									and v.id_venta=cvm.id_venta
									and m.id=cvm.id_mercancia
									and m.id_tipo_mercancia=5
									and v.id_user='".$id."'
									and m.sku=me.id
									and (DATEDIFF(now(),v.fecha)<=me.caducidad or me.caducidad=0)");
		}elseif ($id_tipo_mercancia == 2){
			$q = $this->db->query("SELECT v.id_venta,v.fecha,pa.caducidad,DATEDIFF(now(),v.fecha)as dias_activacion FROM venta v,cross_venta_mercancia cvm,mercancia m,paquete_inscripcion pa
									where v.id_estatus='ACT'
									and v.id_venta=cvm.id_venta
									and m.id=cvm.id_mercancia
									and m.id_tipo_mercancia=4
									and v.id_user='".$id."'
									and m.sku=pa.id_paquete
									and (DATEDIFF(now(),v.fecha)<=pa.caducidad or pa.caducidad=0)");
		}elseif($id_tipo_mercancia == 3) {
			$q = $this->db->query("SELECT v.id_venta,v.fecha FROM venta v,cross_venta_mercancia cvm,mercancia m
									where v.id_estatus='ACT'
									and v.id_venta=cvm.id_venta
									and m.id=cvm.id_mercancia
									and (m.id_tipo_mercancia!=4)
									and (m.id_tipo_mercancia!=5)
									and v.id_user='".$id."'");
		}else{
			return false;
		}

		$activacion=$q->result();

		if($activacion)
			return true;

		return false;

	}

	function get_username($id)
	{
		$q=$this->db->query('select * from user_profiles where user_id = "'.$id.'"');
		return $q->result();
	}
	function get_style($id)
	{
	  	$q=$this->db->query('select * from estilo_usuario where id_usuario = '.$id);
	 	return $q->result();
	}

	function get_email($id)
	{
		$q=$this->db->query('select email from users where id = '.$id);
		return $q->result();
	}

	function get_pais($id)
	{
		$q=$this->db->query("select cu.pais as pais,c.Name as nombrePais,c.Code2 as codigo,concat(cu.calle,' ',cu.colonia,' ',cu.municipio,' ',cu.estado)as direccion
								,cu.cp as codigo_postal,cu.estado as estado,cu.municipio as municipio,cu.colonia as colonia,cu.calle as calle
								from cross_dir_user cu,Country c
								where c.Code=cu.pais and cu.id_user = ".$id."");
		return $q->result();
	}

	function username($id)
	{
		$q=$this->db->query('select username from users where id = '.$id);
		return $q->result();
	}
	function emailPagos()
	{
		$q=$this->db->query(' SELECT email FROM emails_departamentos LIMIT 0 , 1');
		return $q->result();
	}

	function setArrayVarchar($array){
		$ArrayVarchar = array();
		foreach ($array as $key){
			if(!preg_match('/^[0-9]{1,}$/', $key)){
				$key = '\''.$key.'\'';
			}
			array_push($ArrayVarchar, $key);
		}
		return implode(',',$ArrayVarchar);
	}

}