text:
{
  ("use strict");

  var utils = __webpack_require__(2);

  var transformData = __webpack_require__(19);

  var isCancel = __webpack_require__(20);

  var defaults = __webpack_require__(6);

  function throwIfCancellationRequested(config) {
    if (config.cancelToken) {
      config.cancelToken.throwIfRequested();
    }
  }

  module.exports = function dispatchRequest(config) {
    throwIfCancellationRequested(config);
    config.headers = config.headers || {};
    config.data = transformData(
      config.data,
      config.headers,
      config.transformRequest
    );
    config.headers = utils.merge(
      config.headers.common || {},
      config.headers[config.method] || {},
      config.headers || {}
    );
    utils.forEach(
      ["delete", "get", "head", "post", "put", "patch", "common"],
      function cleanHeaderConfig(method) {
        delete config.headers[method];
      }
    );
    var adapter = config.adapter || defaults.adapter;
    return adapter(config).then(
      function onAdapterResolution(response) {
        throwIfCancellationRequested(config);
        response.data = transformData(
          response.data,
          response.headers,
          config.transformResponse
        );
        return response;
      },
      function onAdapterRejection(reason) {
        if (!isCancel(reason)) {
          throwIfCancellationRequested(config);

          if (reason && reason.response) {
            reason.response.data = transformData(
              reason.response.data,
              reason.response.headers,
              config.transformResponse
            );
          }
        }

        return Promise.reject(reason);
      }
    );
  };
}


text:
pub mod impls;
mod merkle_hasher;
mod merkleize_padded;
mod merkleize_standard;

pub use merkle_hasher::{Error, MerkleHasher};
pub use merkleize_padded::merkleize_padded;
pub use merkleize_standard::merkleize_standard;

use eth2_hashing::{hash_fixed, ZERO_HASHES, ZERO_HASHES_MAX_INDEX};
use smallvec::SmallVec;

pub const BYTES_PER_CHUNK: usize = 32;
pub const HASHSIZE: usize = 32;
pub const MERKLE_HASH_CHUNK: usize = 2 * BYTES_PER_CHUNK;
pub const MAX_UNION_SELECTOR: u8 = 127;
pub const SMALLVEC_SIZE: usize = 32;

pub type Hash256 = ethereum_types::H256;
pub type PackedEncoding = SmallVec<[u8; SMALLVEC_SIZE]>;

/// Convenience method for `MerkleHasher` which also provides some fast-paths for small trees.
///
/// `minimum_leaf_count` will only be used if it is greater than or equal to the minimum number of leaves that can be created from `bytes`.
pub fn merkle_root(bytes: &[u8], minimum_leaf_count: usize) -> Hash256 {
    let leaves = std::cmp::max(
        (bytes.len() + (HASHSIZE - 1)) / HASHSIZE,
        minimum_leaf_count,
    );

    if leaves == 0 {
        // If there are no bytes then the hash is always zero.
        Hash256::zero()
    } else if leaves == 1 {
        // If there is only one leaf, the hash is always those leaf bytes padded out to 32-bytes.
        let mut hash = [0; HASHSIZE];
        hash[0..bytes.len()].copy_from_slice(bytes);
        Hash256::from_slice(&hash)
    } else if leaves == 2 {
        // If there are only two leaves (this is common with BLS pubkeys), we can avoid some
        // overhead with `MerkleHasher` and just do a simple 3-node tree here.
        let mut leaves = [0; HASHSIZE * 2];
        leaves[0..bytes.len()].copy_from_slice(bytes);

        Hash256::from_slice(&hash_fixed(&leaves))
    } else {
        // If there are 3 or more leaves, use `MerkleHasher`.
        let mut hasher = MerkleHasher::with_leaves(leaves);
        hasher
            .write(bytes)
            .expect("the number of leaves is adequate for the number of bytes");
        hasher
            .finish()
            .expect("the number of leaves is adequate for the number of bytes")
    }
}

/// Returns the node created by hashing `root` and `length`.
///
/// Used in `TreeHash` for inserting the length of a list above it's root.
pub fn mix_in_length(root: &Hash256, length: usize) -> Hash256 {
    let usize_len = std::mem::size_of::<usize>();

    let mut length_bytes = [0; BYTES_PER_CHUNK];
    length_bytes[0..usize_len].copy_from_slice(&length.to_le_bytes());

    Hash256::from_slice(&eth2_hashing::hash32_concat(root.as_bytes(), &length_bytes)[..])
}

/// Returns `Some(root)` created by hashing `root` and `selector`, if `selector <=
/// MAX_UNION_SELECTOR`. Otherwise, returns `None`.
///
/// Used in `TreeHash` for the "union" type.
///
/// ## Specification
///
/// ```ignore,text
/// mix_in_selector: Given a Merkle root root and a type selector selector ("uint256" little-endian
/// serialization) return hash(root + selector).
/// ```
///
/// https://github.com/ethereum/consensus-specs/blob/v1.1.0-beta.3/ssz/simple-serialize.md#union
pub fn mix_in_selector(root: &Hash256, selector: u8) -> Option<Hash256> {
    if selector > MAX_UNION_SELECTOR {
        return None;
    }

    let mut chunk = [0; BYTES_PER_CHUNK];
    chunk[0] = selector;

    let root = eth2_hashing::hash32_concat(root.as_bytes(), &chunk);
    Some(Hash256::from_slice(&root))
}

/// Returns a cached padding node for a given height.
fn get_zero_hash(height: usize) -> &'static [u8] {
    if height <= ZERO_HASHES_MAX_INDEX {
        &ZERO_HASHES[height]
    } else {
        panic!("Tree exceeds MAX_TREE_DEPTH of {}", ZERO_HASHES_MAX_INDEX)
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum TreeHashType {
    Basic,
    Vector,
    List,
    Container,
}

pub trait TreeHash {
    fn tree_hash_type() -> TreeHashType;

    fn tree_hash_packed_encoding(&self) -> PackedEncoding;

    fn tree_hash_packing_factor() -> usize;

    fn tree_hash_root(&self) -> Hash256;
}

/// Punch through references.
impl<'a, T> TreeHash for &'a T
where
    T: TreeHash,
{
    fn tree_hash_type() -> TreeHashType {
        T::tree_hash_type()
    }

    fn tree_hash_packed_encoding(&self) -> PackedEncoding {
        T::tree_hash_packed_encoding(*self)
    }

    fn tree_hash_packing_factor() -> usize {
        T::tree_hash_packing_factor()
    }

    fn tree_hash_root(&self) -> Hash256 {
        T::tree_hash_root(*self)
    }
}

#[macro_export]
macro_rules! tree_hash_ssz_encoding_as_vector {
    ($type: ident) => {
        impl tree_hash::TreeHash for $type {
            fn tree_hash_type() -> tree_hash::TreeHashType {
                tree_hash::TreeHashType::Vector
            }

            fn tree_hash_packed_encoding(&self) -> PackedEncoding {
                unreachable!("Vector should never be packed.")
            }

            fn tree_hash_packing_factor() -> usize {
                unreachable!("Vector should never be packed.")
            }

            fn tree_hash_root(&self) -> Vec<u8> {
                tree_hash::merkle_root(&ssz::ssz_encode(self))
            }
        }
    };
}

#[macro_export]
macro_rules! tree_hash_ssz_encoding_as_list {
    ($type: ident) => {
        impl tree_hash::TreeHash for $type {
            fn tree_hash_type() -> tree_hash::TreeHashType {
                tree_hash::TreeHashType::List
            }

            fn tree_hash_packed_encoding(&self) -> PackedEncoding {
                unreachable!("List should never be packed.")
            }

            fn tree_hash_packing_factor() -> usize {
                unreachable!("List should never be packed.")
            }

            fn tree_hash_root(&self) -> Vec<u8> {
                ssz::ssz_encode(self).tree_hash_root()
            }
        }
    };
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn mix_length() {
        let hash = {
            let mut preimage = vec![42; BYTES_PER_CHUNK];
            preimage.append(&mut vec![42]);
            preimage.append(&mut vec![0; BYTES_PER_CHUNK - 1]);
            eth2_hashing::hash(&preimage)
        };

        assert_eq!(
            mix_in_length(&Hash256::from_slice(&[42; BYTES_PER_CHUNK]), 42).as_bytes(),
            &hash[..]
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function ( $ ) {

    $.fn.inputLengthLimit = function(options) {
        var settings = $.extend({
            maxLen: 255,
            mes: "Chars rest: %",
            mesCssClass: "jq_length_limit_mes",
            mesTag: "span",
            mesReplaceChar: "%"
        }, options );

        this.each(function() {
            var len = $(this).val().length;
            var rest = settings.maxLen < len ? 0 : settings.maxLen - len;
            $(this).after("<" + settings.mesTag + " class=\"" + settings.mesCssClass + "\">"
                              + settings.mes.replace(settings.mesReplaceChar, rest)
                              + "</" + settings.mesTag + ">");

            $(this).keyup(function () {
                var len = $(this).val().length;
                var rest = settings.maxLen < len ? 0 : settings.maxLen - len;
                // console.log("Len: " + len + " of " + settings.maxLen + " (rest: " + rest + ")");
                $(this).next("." + settings.mesCssClass).text(settings.mes.replace(settings.mesReplaceChar, rest));

                if(rest < 1) {
                    limitedText = $(this).val().substr(0, settings.maxLen);
                    $(this).val(limitedText);
                }
            });

        });

        return this;
    };

}( jQuery ));


text:
namespace arangodb {
class ClusterRestExportHandler : public RestVocbaseBaseHandler {
 public:
  ClusterRestExportHandler(application_features::ApplicationServer&,
                           GeneralRequest*, GeneralResponse*);

 public:
  char const* name() const override final { return "ClusterRestExportHandler"; }
  RequestLane lane() const override final { return RequestLane::CLIENT_SLOW; }
  RestStatus execute() override;
};
}  // namespace arangodb

#endif


text:
package io.tek256.render;

import org.joml.Vector3f;

public class Material {
	public static final Vector3f DEFAULT_COLOR = new Vector3f(1f,1f,1f);
	private Vector3f color;
	private float reflect;
	private Texture texture,normalMap;
	private boolean destroyed = false;

	public Material(){
		color = DEFAULT_COLOR;
		reflect = 0;
	}

	public Material(float r, float g, float b){
		this.color = new Vector3f(r,g,b);
		reflect = 0;
	}

	public Material(Vector3f color){
		this.color = color;
		reflect = 0;
	}

	public Material(float r, float g, float b, float reflect){
		this.color = new Vector3f(r,g,b);
		this.reflect = reflect;
	}

	public Material(Vector3f color, float reflect){
		this.color = color;
		this.reflect = reflect;
	}

	public Material(Texture texture){
		this.color = DEFAULT_COLOR;
		reflect = 0;
		this.texture = texture;
	}

	public Material(Texture texture, Texture normalMap){
		this.color = DEFAULT_COLOR;
		reflect = 0f;
		this.texture = texture;
		this.normalMap = normalMap;
	}

	public Material(Vector3f color, Texture texture){
		this.color = color;
		reflect = 0;
		this.texture = texture;
	}

	public Material(Vector3f color, float reflect, Texture texture){
		this.color = color;
		this.reflect = reflect;
		this.texture = texture;
	}

	public Material(Vector3f color, float reflect, Texture texture, Texture normalMap){
		this.color = color;
		this.reflect = reflect;
		this.texture = texture;
		this.normalMap = normalMap;
	}

	public void setColor(Vector3f color){
		if(destroyed) return;
		this.color = color;
	}

	public Vector3f getColor(){
		if(destroyed) return null;
		return color;
	}

	public void setReflect(float reflect){
		if(destroyed) return;
		this.reflect = reflect;
	}

	public float getReflect(){
		if(destroyed) return -1f;
		return reflect;
	}

	public void setTexture(Texture texture){
		if(destroyed) return;
		this.texture = texture;
	}

	public Texture getTexture(){
		if(destroyed) return null;
		return texture;
	}

	public boolean hasTexture(){
		if(destroyed) return false;
		return texture != null;
	}

	public void setNormalMap(Texture normalMap){
		if(destroyed) return;
		this.normalMap = normalMap;
	}

	public Texture getNormalMap(){
		if(destroyed) return null;
		return normalMap;
	}

	public boolean hasNormalMap(){
		if(destroyed) return false;
		return normalMap != null;
	}

	public void destroy(){
		destroyed = true;
		if(texture != null)
			texture.destroy();
		if(normalMap != null)
			normalMap.destroy();
	}

	public boolean isDestroyed(){
		return destroyed;
	}
}


text:
Release
=======

Although not very tricky, it is quite easy to deploy something that
doesn't quite work as expected. The following steps navigate a through
some of the release gotchas and will hopefully result in a successful
release.

STEPS:
------

1. let other contributors know that you are preparing a release and to hold off on merging PRs or pushing new code
* ensure you using the latest stable node and iojs (but not v0.13.x for now)
   as it has a broken zlib which causes it to publish corrupted modules)
* run `./bin/changelog` and add output to `CHANGELOG.md`
* edit changelog output to be as user-friendly as possible (drop [INTERNAL] changes etc.)
* bump `package.json` version
* `./bin/prepare-release`
* `cd to/someplace/to/test/`
* ensure `ember version` is the newly packaged version
* ensure new project generation works  `ember new my-cool-test-project`
  this will fail with: `version not found: ember-cli@version`
* fixup deps: `cd my-cool-test-project`
* link your local ember-cli  `npm link ember-cli`
* install other deps: `npm i && bower i`
* test the server: `ember s`
* test other things like generators and live-reload
* generate a http mock `ember g http-mock my-http-mock`
* test upgrades of other apps

If everything went well, release:

Please note, we have must have an extremely low tolerance for quirks
and failures we do not want our users to endure any extra pain.

1. go back to ember-cli directory
* `git add` the modified `package.json` and `CHANGELOG.md`
* Commit the changes `git commit -m "Release vx.y.z"` and push `git push`
* `git tag "vx.y.z"`
* `git push --tags`
* publish to npm
* `npm publish ./ember-cli-<version>.tgz`

Test published version

1. `npm uninstall -g ember-cli`
* `npm cache clear`
* `npm install -g ember-cli`
* ensure version is as expected `ember version`
* ensure new project generates
* ensure old project upgrades nicely

Tag the release
1. Under `Releases` on GitHub choose `Draft New Release`
* enter the new version number as the tag prefixed with `v` e.g. (`v0.1.12`)
* for release title choose a great name, no pressure
* in the description paste the upgrade instructions from the previous release, followed by the new CHANGELOG entry
* publish the release

Update the site

1. check out gh-pages
* update `_config.yml` version
* update `gh-pages/_posts/2012-01-01-changelog.md`


text:
class Singer < ActiveRecord::Base
end


text:
~~~
CREATE TABLE `wiki` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `scope` varchar(255) NOT NULL,
  `created` int(11) NOT NULL DEFAULT '0',
  `modified` int(11) NOT NULL DEFAULT '0',
  `title` varchar(255) NOT NULL,
  `markdown` mediumtext NOT NULL,
  `html` mediumtext NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_title` (`scope`,`title`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8;

CREATE TABLE `wiki_links` (
  `wiki_id` int(11) unsigned NOT NULL,
  `link` varchar(255) NOT NULL,
  PRIMARY KEY (`wiki_id`,`link`),
  KEY `fk_wiki_id` (`wiki_id`),
  CONSTRAINT `wiki_links_ibfk_1` FOREIGN KEY (`wiki_id`) REFERENCES `wiki` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
~~~

## PostgreSQL

Not yet, but we plan to...


text:
    ::mojo::internal::LogMessage(__FILE__, __LINE__, \
                                 MOJO_LOG_LEVEL_ ## level).stream()

#define MOJO_LAZY_LOG_STREAM(level, condition) \
    !(condition) ? \
        (void) 0 : \
        ::mojo::internal::VoidifyOstream() & MOJO_LOG_STREAM(level)

#define MOJO_SHOULD_LOG(level) \
    (MOJO_LOG_LEVEL_ ## level >= \
     ::mojo::Environment::GetDefaultLogger()->GetMinimumLogLevel())

#define MOJO_LOG(level) \
    MOJO_LAZY_LOG_STREAM(level, MOJO_SHOULD_LOG(level))

#define MOJO_LOG_IF(level, condition) \
    MOJO_LAZY_LOG_STREAM(level, MOJO_SHOULD_LOG(level) && (condition))

#define MOJO_CHECK(condition) \
    MOJO_LAZY_LOG_STREAM(FATAL, !(condition)) \
        << "Check failed: " #condition ". "

// Note: For non-debug builds, |MOJO_DLOG_IF()| *eliminates* (i.e., doesn't
// compile) the condition, whereas |MOJO_DCHECK()| "neuters" the condition
// (i.e., compiles, but doesn't evaluate).
#ifdef NDEBUG

#define MOJO_DLOG(level) MOJO_LAZY_LOG_STREAM(level, false)
#define MOJO_DLOG_IF(level, condition) MOJO_LAZY_LOG_STREAM(level, false)
#define MOJO_DCHECK(condition) MOJO_LAZY_LOG_STREAM(FATAL, false && (condition))

#else

#define MOJO_DLOG(level) MOJO_LOG(level)
#define MOJO_DLOG_IF(level, condition) MOJO_LOG_IF(level, condition)
#define MOJO_DCHECK(condition) MOJO_CHECK(condition)

#endif  // NDEBUG

namespace mojo {
namespace internal {

class LogMessage {
 public:
  LogMessage(const char* file, int line, MojoLogLevel log_level);
  ~LogMessage();

  std::ostream& stream() { return stream_; }

 private:
  const MojoLogLevel log_level_;
  std::ostringstream stream_;

  MOJO_DISALLOW_COPY_AND_ASSIGN(LogMessage);
};

// Used to ignore a stream.
struct VoidifyOstream {
  // Use & since it has precedence lower than << but higher than ?:.
  void operator&(std::ostream&) {}
};

}  // namespace internal
}  // namespace mojo

#endif  // MOJO_PUBLIC_CPP_ENVIRONMENT_LOGGING_H_


text:
GlobalValueModule = GlobalValueModule or BeardLib:ModuleClass("GlobalValue", ItemModuleBase)

function GlobalValueModule:init(...)
    self.clean_table = table.add(clone(self.clean_table), {{param = "color", action = "normalize"}})
    return GlobalValueModule.super.init(self, ...)
end

function GlobalValueModule:RegisterHook()
    Hooks:PostHook(LootDropTweakData, "init", self._config.id .. "AddGlobalValueData", function(loot_self, tweak_data)
        if loot_self.global_values[self._config.id] and not self._config.overwrite then
            self:Err("Global value with key %s already exists! overwrite should be set to true if this is intentional.")
            return
        end

        loot_self.global_values[self._config.id] = table.merge({
            name_id = "bm_global_value_" .. self._config.id,
            desc_id = "menu_l_global_value_" .. self._config.id,
            color = Color.white,
            dlc = false,
            chance = 1,
            custom = true,
            value_multiplier = 1,
            track = false,
            sort_number = 0,
            category = not self._config.is_category and "mod",
        }, self._config)

        table.insert(loot_self.global_value_list_index, self._config.id)
        loot_self.global_value_list_map[self._config.id] = #loot_self.global_value_list_index
    end)
end


text:
DEV = 'Module under development.'

def print_development():
    print(DEV)


text:
package hello;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.util.FileSystemUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init() {
        return (args) -> {
            FileSystemUtils.deleteRecursively(new File(FileUploadController.ROOT));
            Files.createDirectory(Paths.get(FileUploadController.ROOT));
        };
    }
}


text:
QStringList CriteriaBuilder::toList()
{
    return m_list;
}

void CriteriaBuilder::insert(const QString key, const QVariant value) {
    QString typeName = value.typeName();
    QString format;
    bool isInt;
    value.toInt(&isInt);
    if(typeName.compare("QString")==0 && !isInt)
        format = "%1='%2'";
    else
        format = "%1=%2";
    m_list << QString(format).arg(key).arg(value.toString());
}

void CriteriaBuilder::insertLessOrEq(const QString key, const QVariant value) {
    if(!isNumeric(value)) return;
    m_list << QString("%1<=%2").arg(key).arg(value.toString());
}

void CriteriaBuilder::insertGrtOrEq(const QString key, const QVariant value) {
    if(!isNumeric(value)) return;
    m_list << QString("%1>=%2").arg(key).arg(value.toString());
}

void CriteriaBuilder::insertLess(const QString key, const QVariant value) {
    if(!isNumeric(value)) return;
    m_list << QString("%1<%2").arg(key).arg(value.toString());
}

void CriteriaBuilder::insertGrtr(const QString key, const QVariant value) {
    if(!isNumeric(value)) return;
    m_list << QString("%1>%2").arg(key).arg(value.toString());
}

bool CriteriaBuilder::isNumeric(QVariant value)
{
    QString typeName = QString(value.typeName());
    bool isInt      = (typeName == "int");
    bool isDouble   = (typeName == "double");
    bool isFloat    = (typeName == "float");
    bool isLong     = (typeName == "long");
    return isInt || isDouble || isFloat || isLong;
}


text:
$(document).ready(function(){
  $('#login-trigger').click(function(){
    $(this).next('#login-content').slideToggle();
    $(this).toggleClass('active');

    if ($(this).hasClass('active')) $(this).find('span').html('▲')
      else $(this).find('span').html('▼')
    })
});

$(document).ready(function(){
  $('#admin-page-trigger').click(function(){
    $(this).next('#admin-page-content').slideToggle();
    $(this).toggleClass('active');

    if ($(this).hasClass('active')) $(this).find('span').html('▲')
      else $(this).find('span').html('▼')
    })
});


text:
import TextureBase from "./TextureBase";
import BitmapData from "./../../display/BitmapData";
import ByteArray from "./../../utils/ByteArray";

declare namespace openfl.display3D.textures {

	/*@:final*/ export class Texture extends TextureBase {

		public uploadCompressedTextureFromByteArray (data:ByteArray, byteArrayOffset:number, async?:boolean):void;
		public uploadFromBitmapData (source:BitmapData, miplevel?:number):void;
		public uploadFromByteArray (data:ByteArray, byteArrayOffset:number, miplevel?:number):void;

	}

}

export default openfl.display3D.textures.Texture;


text:
package com.intellij.idea;

import com.intellij.ide.IdeBundle;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.JetBrainsProtocolHandler;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Consumer;
import com.intellij.util.NotNullProducer;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.io.BuiltInServer;
import org.jetbrains.io.MessageDecoder;

import java.io.*;
import java.lang.management.ManagementFactory;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;

/**
 * @author mike
 */
public final class SocketLock {
  public enum ActivateStatus {ACTIVATED, NO_INSTANCE, CANNOT_ACTIVATE}

  private static final String PORT_FILE = "port";
  private static final String PORT_LOCK_FILE = "port.lock";
  private static final String TOKEN_FILE = "token";

  private static final String ACTIVATE_COMMAND = "activate ";
  private static final String PID_COMMAND = "pid";
  private static final String PATHS_EOT_RESPONSE = "---";
  private static final String OK_RESPONSE = "ok";

  private final String myConfigPath;
  private final String mySystemPath;
  private final AtomicReference<Consumer<List<String>>> myActivateListener = new AtomicReference<>();
  private String myToken;
  private BuiltInServer myServer;

  public SocketLock(@NotNull String configPath, @NotNull String systemPath) {
    myConfigPath = canonicalPath(configPath);
    mySystemPath = canonicalPath(systemPath);
  }

  public void setExternalInstanceListener(@Nullable Consumer<List<String>> consumer) {
    myActivateListener.set(consumer);
  }

  public void dispose() {
    log("enter: dispose()");

    BuiltInServer server = myServer;
    if (server == null) return;

    try {
      Disposer.dispose(server);
    }
    finally {
      try {
        underLocks(() -> {
          FileUtil.delete(new File(myConfigPath, PORT_FILE));
          FileUtil.delete(new File(mySystemPath, PORT_FILE));
          FileUtil.delete(new File(mySystemPath, TOKEN_FILE));
          return null;
        });
      }
      catch (Exception e) {
        Logger.getInstance(SocketLock.class).warn(e);
      }
    }
  }

  @Nullable
  public BuiltInServer getServer() {
    return myServer;
  }

  @NotNull
  public ActivateStatus lock() throws Exception {
    return lock(ArrayUtil.EMPTY_STRING_ARRAY);
  }

  @NotNull
  public ActivateStatus lock(@NotNull String[] args) throws Exception {
    log("enter: lock(config=%s system=%s)", myConfigPath, mySystemPath);

    return underLocks(() -> {
      File portMarkerC = new File(myConfigPath, PORT_FILE);
      File portMarkerS = new File(mySystemPath, PORT_FILE);

      MultiMap<Integer, String> portToPath = MultiMap.createSmart();
      addExistingPort(portMarkerC, myConfigPath, portToPath);
      addExistingPort(portMarkerS, mySystemPath, portToPath);
      if (!portToPath.isEmpty()) {
        for (Map.Entry<Integer, Collection<String>> entry : portToPath.entrySet()) {
          ActivateStatus status = tryActivate(entry.getKey(), entry.getValue(), args);
          if (status != ActivateStatus.NO_INSTANCE) {
            log("exit: lock(): " + status);
            return status;
          }
        }
      }

      if (isShutdownCommand()) {
        System.exit(0);
      }

      myToken = UUID.randomUUID().toString();
      String[] lockedPaths = {myConfigPath, mySystemPath};
      int workerCount = PlatformUtils.isIdeaCommunity() || PlatformUtils.isDatabaseIDE() || PlatformUtils.isCidr() ? 1 : 2;
      NotNullProducer<ChannelHandler> handler = () -> new MyChannelInboundHandler(lockedPaths, myActivateListener, myToken);
      myServer = BuiltInServer.startNioOrOio(workerCount, 6942, 50, false, handler);

      byte[] portBytes = Integer.toString(myServer.getPort()).getBytes(CharsetToolkit.UTF8_CHARSET);
      FileUtil.writeToFile(portMarkerC, portBytes);
      FileUtil.writeToFile(portMarkerS, portBytes);

      File tokenFile = new File(mySystemPath, TOKEN_FILE);
      FileUtil.writeToFile(tokenFile, myToken.getBytes(CharsetToolkit.UTF8_CHARSET));
      PosixFileAttributeView view = Files.getFileAttributeView(tokenFile.toPath(), PosixFileAttributeView.class);
      if (view != null) {
        try {
          view.setPermissions(ContainerUtil.newHashSet(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE));
        }
        catch (IOException e) {
          log(e);
        }
      }

      log("exit: lock(): succeed");
      return ActivateStatus.NO_INSTANCE;
    });
  }

  private <V> V underLocks(@NotNull Callable<V> action) throws Exception {
    FileUtilRt.createDirectory(new File(myConfigPath));
    try (@SuppressWarnings("unused") FileOutputStream lock1 = new FileOutputStream(new File(myConfigPath, PORT_LOCK_FILE), true)) {
      FileUtilRt.createDirectory(new File(mySystemPath));
      try (@SuppressWarnings("unused") FileOutputStream lock2 = new FileOutputStream(new File(mySystemPath, PORT_LOCK_FILE), true)) {
        return action.call();
      }
    }
  }

  private static void addExistingPort(@NotNull File portMarker, @NotNull String path, @NotNull MultiMap<Integer, String> portToPath) {
    if (portMarker.exists()) {
      try {
        portToPath.putValue(Integer.parseInt(FileUtilRt.loadFile(portMarker)), path);
      }
      catch (Exception e) {
        log(e);
        // don't delete - we overwrite it on write in any case
      }
    }
  }

  @NotNull
  private ActivateStatus tryActivate(int portNumber, @NotNull Collection<String> paths, @NotNull String[] args) {
    log("trying: port=%s", portNumber);
    args = checkForJetBrainsProtocolCommand(args);
    try {
      try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), portNumber)) {
        socket.setSoTimeout(1000);

        boolean result = false;
        @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") DataInputStream in = new DataInputStream(socket.getInputStream());
        while (true) {
          try {
            String path = in.readUTF();
            log("read: path=%s", path);
            if (PATHS_EOT_RESPONSE.equals(path)) {
              break;
            }
            else if (paths.contains(path)) {
              result = true;  // don't break - read all input
            }
          }
          catch (IOException e) {
            log("read: %s", e.getMessage());
            break;
          }
        }

        if (result) {
          try {
            String token = FileUtil.loadFile(new File(mySystemPath, TOKEN_FILE));
            @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(ACTIVATE_COMMAND + token + "\0" + new File(".").getAbsolutePath() + "\0" + StringUtil.join(args, "\0"));
            out.flush();
            String response = in.readUTF();
            log("read: response=%s", response);
            if (response.equals(OK_RESPONSE)) {
              if (isShutdownCommand()) {
                printPID(portNumber);
              }
              return ActivateStatus.ACTIVATED;
            }
          }
          catch (IOException e) {
            log(e);
          }

          return ActivateStatus.CANNOT_ACTIVATE;
        }
      }
    }
    catch (ConnectException e) {
      log("%s (stale port file?)", e.getMessage());
    }
    catch (IOException e) {
      log(e);
    }

    return ActivateStatus.NO_INSTANCE;
  }

  @SuppressWarnings("ALL")
  private static void printPID(int port) {
    try {
      Socket socket = new Socket(InetAddress.getLoopbackAddress(), port);
      socket.setSoTimeout(1000);
      @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") DataOutputStream out = new DataOutputStream(socket.getOutputStream());
      out.writeUTF(PID_COMMAND);
      DataInputStream in = new DataInputStream(socket.getInputStream());
      int pid = 0;
      while (true) {
        try {
          String s = in.readUTF();
          if (Pattern.matches("[0-9]+@.*", s)) {
            pid = Integer.parseInt(s.substring(0, s.indexOf('@')));
            System.err.println(pid);
          }
        }catch (IOException e) {
          break;
        }
      }
    }
    catch (Exception ignore) {
    }
  }

  private static boolean isShutdownCommand() {
    return "shutdown".equals(JetBrainsProtocolHandler.getCommand());
  }

  private static String[] checkForJetBrainsProtocolCommand(String[] args) {
    final String jbUrl = System.getProperty(JetBrainsProtocolHandler.class.getName());
    if (jbUrl != null) {
      return new String[]{jbUrl};
    }
    return args;
  }

  private static class MyChannelInboundHandler extends MessageDecoder {
    private enum State {HEADER, CONTENT}

    private final String[] myLockedPaths;
    private final AtomicReference<Consumer<List<String>>> myActivateListener;
    private final String myToken;
    private State myState = State.HEADER;

    public MyChannelInboundHandler(@NotNull String[] lockedPaths,
                                   @NotNull AtomicReference<Consumer<List<String>>> activateListener,
                                   @NotNull String token) {
      myLockedPaths = lockedPaths;
      myActivateListener = activateListener;
      myToken = token;
    }

    @Override
    public void channelActive(ChannelHandlerContext context) throws Exception {
      ByteBuf buffer = context.alloc().ioBuffer(1024);
      boolean success = false;
      try {
        ByteBufOutputStream out = new ByteBufOutputStream(buffer);
        for (String path : myLockedPaths) out.writeUTF(path);
        out.writeUTF(PATHS_EOT_RESPONSE);
        out.close();
        success = true;
      }
      finally {
        if (!success) {
          buffer.release();
        }
      }
      context.writeAndFlush(buffer);
    }

    @Override
    protected void messageReceived(@NotNull ChannelHandlerContext context, @NotNull ByteBuf input) throws Exception {
      while (true) {
        switch (myState) {
          case HEADER: {
            ByteBuf buffer = getBufferIfSufficient(input, 2, context);
            if (buffer == null) {
              return;
            }

            contentLength = buffer.readUnsignedShort();
            if (contentLength > 8192) {
              context.close();
              return;
            }
            myState = State.CONTENT;
          }
          break;

          case CONTENT: {
            CharSequence command = readChars(input);
            if (command == null) {
              return;
            }

            if (StringUtil.startsWith(command, PID_COMMAND)) {
              ByteBuf buffer = context.alloc().ioBuffer();
              ByteBufOutputStream out = new ByteBufOutputStream(buffer);
              String name = ManagementFactory.getRuntimeMXBean().getName();
              out.writeUTF(name);
              out.close();
              context.writeAndFlush(buffer);
            }

            if (StringUtil.startsWith(command, ACTIVATE_COMMAND)) {
              String data = command.subSequence(ACTIVATE_COMMAND.length(), command.length()).toString();
              List<String> args = StringUtil.split(data, data.contains("\0") ? "\0" : "\uFFFD");

              boolean tokenOK = !args.isEmpty() && myToken.equals(args.get(0));
              if (!tokenOK) {
                log(new UnsupportedOperationException("unauthorized request: " + command));
                Notifications.Bus.notify(new Notification(
                  Notifications.SYSTEM_MESSAGES_GROUP_ID,
                  IdeBundle.message("activation.auth.title"),
                  IdeBundle.message("activation.auth.message"),
                  NotificationType.WARNING));
              }
              else {
                Consumer<List<String>> listener = myActivateListener.get();
                if (listener != null) {
                  listener.consume(args.subList(1, args.size()));
                }
              }

              ByteBuf buffer = context.alloc().ioBuffer(4);
              ByteBufOutputStream out = new ByteBufOutputStream(buffer);
              out.writeUTF(OK_RESPONSE);
              out.close();
              context.writeAndFlush(buffer);
            }
            context.close();
          }
          break;
        }
      }
    }
  }

  @NotNull
  private static String canonicalPath(@NotNull String configPath) {
    try {
      return new File(configPath).getCanonicalPath();
    }
    catch (IOException ignore) {
      return configPath;
    }
  }

  private static void log(Exception e) {
    Logger.getInstance(SocketLock.class).warn(e);
  }

  private static void log(String format, Object... args) {
    Logger logger = Logger.getInstance(SocketLock.class);
    if (logger.isDebugEnabled()) {
      logger.debug(String.format(format, args));
    }
  }
}


text:
import urllib2
import simplejson

url='''
https://api.twitter.com/1/statuses//user_timeline.json?include_entities=true&include_rts=true%screen_name=twitterapi&count=2
'''

if __name__ == "__main__":
	req = urllib2.Request(url)
	opener = urllib2.build_opener()
	f = opener.open(req)
	json = simplejosn.load(f)


text:
package org.smart4j.framework.mvc.fault;

/**
 * 授权异常(当权限无效时抛出)
 *
 * @author huangyong
 * @since 2.1
 */
public class AuthzException extends RuntimeException {

    /**
	 *
	 */
	private static final long serialVersionUID = 3561270841352246235L;

	public AuthzException() {
        super();
    }

    public AuthzException(String message) {
        super(message);
    }

    public AuthzException(String message, Throwable cause) {
        super(message, cause);
    }

    public AuthzException(Throwable cause) {
        super(cause);
    }
}


text:
<?php

namespace app\models\core\Form;

abstract class BaseFormFilter implements  FormFilterInterface
{

    // options for filter
    protected $options;

    /**
     * Injects filter options in constructor
     *
     * @param array $options
     */
    function __construct(array $options = array())
    {
        $this->options = $options;
    }

    /**
     * To stablish default options in extended classes
     *
     * @param array $options
     */
    function setDefaultOptions(array $options)
    {
        $this->options = array_merge($options,$this->options);
    }

    /**
     * Sample filter that do nothing
     *
     * @return mixed
     */
    function filter($subject)
    {
        return $subject;
    }

}


text:
angular.module('activitiApp').directive('aaTaskDefault', function () {
    return {
        restrict: 'E',

        templateUrl: "views/directives/taskDefault.html"

    };
});


text:
package com.sl.algorithms.core.list.reversal;

import static com.sl.algorithms.core.list.ListNode.createLinkedList;
import static com.sl.algorithms.core.utils.LinkedListOps.reverse;
import static com.sl.algorithms.core.utils.LinkedListOps.reverseListInGroups;

import com.sl.algorithms.core.list.ListNode;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class LinkedListReversalTest {

  private ListNode<Integer> testNode;

  @Before
  public void createList() {
    testNode = createLinkedList(new Integer[]{1, 2, 3, 4, 5});
  }

  @Test
  public void testReverse() {
    Assert.assertNull(reverse(null));

    ListNode<Integer> singleNode = new ListNode<>(1);
    Assert.assertEquals(singleNode, reverse(singleNode));

    ListNode<Integer> pair = reverse(createLinkedList(new Integer[]{1, 2}));
    Assert.assertEquals("[2,1]", pair.toString());

    Assert.assertEquals("[5,4,3,2,1]", reverse(testNode).toString());
  }

  @Test
  public void testReverseInGroups() {
    {
      Assert.assertNull(reverseListInGroups(null, 1));
    }
    {
      ListNode<Integer> singleNode = new ListNode<>(1);
      Assert.assertTrue(singleNode.equals(reverseListInGroups(singleNode, 1)));
    }
    {
      ListNode<Integer> pairNode = createLinkedList(new Integer[]{1, 2});
      Assert.assertEquals("[2,1]", reverseListInGroups(pairNode, 2).toString());
      pairNode = createLinkedList(new Integer[]{1, 2});
      Assert.assertEquals("[1,2]", reverseListInGroups(pairNode, 3).toString());
    }
    {
      Assert.assertEquals(testNode, reverseListInGroups(testNode, 0));
      Assert.assertEquals(testNode, reverseListInGroups(testNode, 1));
    }
    {
      Assert.assertEquals("[2,1,4,3,5]", reverseListInGroups(testNode.clone(), 2).toString());
    }
    {
      Assert.assertEquals("[3,2,1,4,5]", reverseListInGroups(testNode.clone(), 3).toString());
    }
    {
      Assert.assertEquals("[4,3,2,1,5]", reverseListInGroups(testNode.clone(), 4).toString());
    }
    {
      Assert.assertEquals("[5,4,3,2,1]", reverseListInGroups(testNode.clone(), 5).toString());
    }
    {
      Assert.assertEquals("[1,2,3,4,5]", reverseListInGroups(testNode.clone(), 6).toString());
    }
  }
}


text:
void lpjit_compilerInit(CompilerState* cstate,
                        lua_State* L,
                        Pattern* pattern) {
    cstate->L = L;
    cstate->pattern = pattern;
    cstate->instruction = pattern->code;
    cstate->max_stack_size = lpeg_maxStackIndex(L);
    cstate->has_runtime = 0;
}

int lpjit_offsetOf(CompilerState* cstate,
                   Instruction* instruction) {
    return instruction - cstate->pattern->code;
}

Instruction* lpjit_fromOffset(CompilerState* cstate,
                              int offset) {
    return cstate->pattern->code + offset;
}


text:
export default {
    entry     : 'index.js',
    dest      : 'bundles/angular-datatables.umd.js',
    format    : 'umd',
    external  : [
        '@angular/core',
        '@angular/platform-browser',
        '@angular/common'
    ],
    globals   : {
        '@angular/core': 'ng.core',
        '@angular/platform-browser': 'ng.platform-browser',
        '@angular/common': 'ng.common'
    },
    moduleName: 'angular.datatables'
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace mod_data\external;
defined('MOODLE_INTERNAL') || die();

use core\external\exporter;
use renderer_base;
use external_files;
use external_util;

/**
 * Class for exporting content associated to a record.
 *
 * @copyright  2017 Juan Leyva <juan@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class content_exporter extends exporter {

    protected static function define_properties() {

        return array(
            'id' => array(
                'type' => PARAM_INT,
                'description' => 'Content id.',
            ),
            'fieldid' => array(
                'type' => PARAM_INT,
                'description' => 'The field type of the content.',
                'default' => 0,
            ),
            'recordid' => array(
                'type' => PARAM_INT,
                'description' => 'The record this content belongs to.',
                'default' => 0,
            ),
            'content' => array(
                'type' => PARAM_RAW,
                'description' => 'Contents.',
                'null' => NULL_ALLOWED,
            ),
            'content1' => array(
                'type' => PARAM_RAW,
                'description' => 'Contents.',
                'null' => NULL_ALLOWED,
            ),
            'content2' => array(
                'type' => PARAM_RAW,
                'description' => 'Contents.',
                'null' => NULL_ALLOWED,
            ),
            'content3' => array(
                'type' => PARAM_BOOL,
                'description' => 'Contents.',
                'null' => NULL_ALLOWED,
            ),
            'content4' => array(
                'type' => PARAM_BOOL,
                'description' => 'Contents.',
                'null' => NULL_ALLOWED,
            ),
        );
    }

    protected static function define_related() {
        return array(
            'context' => 'context',
        );
    }

    protected static function define_other_properties() {
        return array(
            'files' => array(
                'type' => external_files::get_properties_for_exporter(),
                'multiple' => true,
                'optional' => true,
            ),
        );
    }

    protected function get_other_values(renderer_base $output) {
        $values = ['files' => external_util::get_area_files($this->related['context']->id, 'mod_data', 'content', $this->data->id)];

        return $values;
    }
}


text:
const webpack = require('webpack');
const config = require("../webpack.config.js");

var compiler = webpack(config);
compiler.run((err, stats) => {
    if (err) {
        console.log(err)
    }
})


text:
'use strict';

const { execSync } = require('child_process');
const execa = require('execa');
const logger = require('./logger');

/**
 * @param {string} path Path to directory (frontend, backend)
 * @param {Object} options
 * @param {boolean} options.useYarn Use yarn instead of npm
 */
function runInstall(path, { useYarn } = {}) {
  return execa(useYarn ? 'yarn' : 'npm', ['install'], {
    cwd: path,
    stdin: 'ignore',
  });
}

/**
 * @param {string} rootPath
 * @param {Object} options
 * @param {boolean} options.useYarn
 */
function runApp(rootPath, { useYarn } = {}) {
  if (useYarn) {
    return execa('yarn', ['develop'], {
      stdio: 'inherit',
      cwd: rootPath,
    });
  } else {
    return execa('npm', ['run', 'develop'], {
      stdio: 'inherit',
      cwd: rootPath,
    });
  }
}

async function initGit(rootPath) {
  try {
    await execa('git', ['init'], {
      cwd: rootPath,
    });
  } catch (err) {
    logger.warn(`Could not initialize a git repository`);
  }

  try {
    await execa(`git`, [`add`, `-A`], { cwd: rootPath });

    execSync(`git commit -m "Create Strapi starter project"`, {
      cwd: rootPath,
    });
  } catch (err) {
    logger.warn(`Could not create initial git commit`);
  }
}

module.exports = {
  runInstall,
  runApp,
  initGit,
};


text:
/*
 * Never include this file directly; use <sys/socket.h> instead.
 */

#ifndef _BITS_SOCKADDR_H
#define _BITS_SOCKADDR_H	1

/* POSIX.1g specifies this type name for the `sa_family' member.  */
typedef unsigned short int sa_family_t;

/* This macro is used to declare the initial common members
   of the data types used for socket addresses, `struct sockaddr',
   `struct sockaddr_in', `struct sockaddr_un', etc.  */

#define	__SOCKADDR_COMMON(sa_prefix) \
  sa_family_t sa_prefix##family

#define __SOCKADDR_COMMON_SIZE	(sizeof (unsigned short int))

#endif	/* bits/sockaddr.h */


text:
/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

namespace Altavant.Fusion.Graphics
{
	public enum PaintMode : byte
	{
		Fill,
		Stroke,
		FillStroke,
		Clip
	}

	public interface IGraphics
	{
		Font Font { get; set; }
		Brush Brush { get; set; }
		Pen Pen { get; set; }
		FontMetrics FontMetrics { get; }
		Matrix Transformation { get; }
		bool AlternateFill { get; set; }
		void SaveClip(float x, float y, float width, float height);
		void RestoreClip();
		void SaveState();
		void RestoreState();
		void Transform(Matrix matrix);
		void Translate(float offsetX, float offsetY);
		void Rotate(float centerX, float centerY, float angle);
		void Scale(float scaleX, float scaleY);
		void Shear(float shearX, float shearY);
		void Skew(float skewX, float skewY);
		float MeasureString(string text);
		void DrawString(float x, float y, string text);
		void DrawRectangle(float x, float y, float width, float height);
		void FillRectangle(float x, float y, float width, float height);
		void ClipRectangle(float x, float y, float width, float height);
		void DrawRectangle(float x, float y, float width, float height, PaintMode mode);
		void DrawRoundRect(float x, float y, float width, float height, float ew, float eh);
		void FillRoundRect(float x, float y, float width, float height, float ew, float eh);
		void ClipRoundRect(float x, float y, float width, float height, float ew, float eh);
		void DrawRoundRect(float x, float y, float width, float height, float ew, float eh, PaintMode mode);
		void DrawLine(float x1, float y1, float x2, float y2);
		void DrawLines(PointCollection points);
		void DrawPolygon(PointCollection points);
		void FillPolygon(PointCollection points);
		void ClipPolygon(PointCollection points);
		void DrawPolygon(PointCollection points, PaintMode mode);
		void DrawEllipse(float x, float y, float width, float height);
		void FillEllipse(float x, float y, float width, float height);
		void ClipEllipse(float x, float y, float width, float height);
		void DrawEllipse(float x, float y, float width, float height, PaintMode mode);
		void DrawArc(float x, float y, float width, float height, float startAngle, float endAngle);
		void FillArc(float x, float y, float width, float height, float startAngle, float endAngle);
		void ClipArc(float x, float y, float width, float height, float startAngle, float endAngle);
		void DrawArc(float x, float y, float width, float height, float startAngle, float endAngle, PaintMode mode);
		void DrawPie(float x, float y, float width, float height, float startAngle, float endAngle);
		void FillPie(float x, float y, float width, float height, float startAngle, float endAngle);
		void ClipPie(float x, float y, float width, float height, float startAngle, float endAngle);
		void DrawPie(float x, float y, float width, float height, float startAngle, float endAngle, PaintMode mode);
		void DrawChord(float x, float y, float width, float height, float startAngle, float endAngle);
		void FillChord(float x, float y, float width, float height, float startAngle, float endAngle);
		void ClipChord(float x, float y, float width, float height, float startAngle, float endAngle);
		void DrawChord(float x, float y, float width, float height, float startAngle, float endAngle, PaintMode mode);
		void DrawCurve(PointCollection points, float tension);
		void DrawClosedCurve(PointCollection points, float tension);
		void FillClosedCurve(PointCollection points, float tension);
		void ClipClosedCurve(PointCollection points, float tension);
		void DrawClosedCurve(PointCollection points, float tension, PaintMode mode);
		void DrawBezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4);
		void DrawBeziers(PointCollection points);
		void FillBeziers(PointCollection points);
		void ClipBeziers(PointCollection points);
		void DrawBeziers(PointCollection points, PaintMode mode);
		void StartShape(PaintMode mode);
		void MoveTo(float x, float y);
		void LineTo(float x, float y);
		void CurveTo(float x1, float y1, float x2, float y2, float x3, float y3);
		void ClosePath();
		void EndShape();
		void DrawImage(Image image, float x, float y, float width, float height);
		void Flush();
	}
}


text:
id: 5900f3e41000cf542c50fef6
title: 'Problem 119: Digit power sum'
challengeType: 5
forumTopicId: 301745
dashedName: problem-119-digit-power-sum
---

# --description--

The number 512 is interesting because it is equal to the sum of its digits raised to some power: $5 + 1 + 2 = 8$, and $8^3 = 512$. Another example of a number with this property is $614656 = 28^4$.

We shall define $a_n$ to be the $n-th$ term of this sequence and insist that a number must contain at least two digits to have a sum.

You are given that $a_2 = 512$ and $a_{10} = 614656$.

Find $a_{30}$.

# --hints--

`digitPowerSum()` should return `248155780267521`.

```js
assert.strictEqual(digitPowerSum(), 248155780267521);
```

# --seed--

## --seed-contents--

```js
function digitPowerSum() {

  return true;
}

digitPowerSum();
```

# --solutions--

```js
// solution required
```


text:
package com.bjond.test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.util.Set;

import org.junit.Assert;
import org.junit.Test;

import com.bjond.utilities.MiscUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.val;

/** JUnit Test Suite TestBrigid
 *
 * @version 0.001 10/16/15mport scala.ScalaHelloWorld;
 * @author Stephen Agneta
 * @since Build 1.000
 *
 */

public class TestUtils {

    /////////////////////////////////////////////////////////////////////////
    //                      Unit Tests below this point                    //
    /////////////////////////////////////////////////////////////////////////

	static public class MyBean {
		@Getter @Setter String prop1;
		@Getter @Setter String prop2;
	}

    @Test
    public void sanityCheck() throws Exception {
        Assert.assertTrue("I ran ok!", true);
        System.out.println("This is a test"); // You should see this in the html report in stdout.
    }

	@Test
	public void testGetNullProperties() throws Exception {

		val o = new MyBean();
		o.setProp1("The secret of life is honesty and fair dealing. If you can fake that, you've got it made.");
		o.setProp2("Man does not control his own fate. The women in his life do that for him.");

		Set<String> nullOnes = MiscUtils.getNullProperties(o);

		assertEquals(0, nullOnes.size());

		o.setProp2(null);
		nullOnes = MiscUtils.getNullProperties(o);

		assertEquals(1, nullOnes.size());
	}

	@Test
	public void testNonNullProperties() throws Exception {

		val o = new MyBean();
		o.setProp1("The secret of life is honesty and fair dealing. If you can fake that, you've got it made.");
		o.setProp2("Man does not control his own fate. The women in his life do that for him.");

		val props = MiscUtils.getNonNullProperties(o);

		// We filter out "Object.getClass()".
		assertFalse(props.containsKey("class"));
		assertEquals(2, props.keySet().size());
	}

    @Test
	public void test_normalizeToNaturalSortOrder() throws Exception {
        final String resultString1 = "aa000000000000000000000000000000000000000000000000000000000000000000000000011bb000000000000000000000000000000000000000000000000000000000000000000000000022cc000000000000000000000000000000000000000000000000000000000000000000000000033ff";
        final String resultString2 = "000000000000000000000000000000000000000000000000000000000000000000000000011aa000000000000000000000000000000000000000000000000000000000000000000000000022bb000000000000000000000000000000000000000000000000000000000000000000000000033cc000000000000000000000000000000000000000000000000000000000000000000000000044";
        final String resultString3 = "000000000000000000000000000000000000000000000000000000000000000000000000111";
        System.out.println("test_normalizeToNaturalSortOrder() invoked");

        final String result = MiscUtils.normalizeToNaturalSortOrder("aa11bb22cc33ff");
        //System.out.println("RESULT: " + result);
        assertThat(result).isEqualTo(resultString1);

        final String result2 = MiscUtils.normalizeToNaturalSortOrder("11aa22bb33cc44");
        //System.out.println("RESULT: " + result2);
        assertThat(result2).isEqualTo(resultString2);

        final String result3 = MiscUtils.normalizeToNaturalSortOrder("111");
        //System.out.println("RESULT: " + result3);
        assertThat(result3).isEqualTo(resultString3);

        final String result4 = MiscUtils.normalizeToNaturalSortOrder("now is the time for all good men");
        //System.out.println("RESULT: " + result4);
        assertThat(result4).isEqualTo("now is the time for all good men");

        // Some more edge cases
        assertThat(MiscUtils.normalizeToNaturalSortOrder("")).isNullOrEmpty();
        assertThat(MiscUtils.normalizeToNaturalSortOrder(null)).isNullOrEmpty();

    }

}


text:
<?php
/*
# ----------------------------------------------------------------------
# SETTINGS - PAYMENT: CONTROL
# ----------------------------------------------------------------------
*/

$_get    = new PAYMENT_GET();
$_update = new PAYMENT_UPDATE();

$payments = $_get->get_payments();

$payment_bank = $_get->get_payment('bank');

/* --- BUTTON HANDLER --- */
if(isset($_POST['btn-payment']) && $_POST['btn-payment'] == 'Save Changes'){

   $payment_id     = filter_var($_POST['account_id'], FILTER_SANITIZE_STRING);
   $type           = filter_var($_POST['method'], FILTER_SANITIZE_STRING);
   $payment_bank   = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
   $payment_number = filter_var($_POST['number'], FILTER_SANITIZE_STRING);
   $payment_name   = filter_var($_POST['account'], FILTER_SANITIZE_STRING);

   if($payment_id == 'new'){
      $_update->insert_account($type, $payment_bank, $payment_number, $payment_name);

      $type = 'success';
      $msg  = 'New payment method successfully saved';
   }else{

      $_update->update_account($payment_bank, $payment_number, $payment_name, $payment_id);

      $type = 'success';
      $msg  = 'Changes successfully saved.';
   }

   $page = 'payment';

   set_alert($type, $msg);
   safe_redirect($page);

}

if(isset($_POST['btn-payment']) && $_POST['btn-payment'] == 'Delete'){

   $payment_id     = filter_var($_POST['account_id'], FILTER_SANITIZE_STRING);

   $_update->delete_account($payment_id);

   $type = 'success';
   $msg  = 'Successfully delete payment method.';

   $page = 'payment';

   set_alert($type, $msg);
   safe_redirect($page);

}
?>


text:
using System;
using KitchenPC.ShoppingLists;

namespace KitchenPC.Ingredients
{
   public class IngredientAggregation : IShoppingListSource
   {
      public Ingredient Ingredient;
      public Amount Amount;

      public IngredientAggregation(Ingredient ingredient)
      {
         this.Ingredient = ingredient;

         if (ingredient != null)
         {
            this.Amount = new Amount();
            this.Amount.Unit = Unit.GetDefaultUnitType(ingredient.ConversionType);
         }
      }

      public IngredientAggregation(Ingredient ingredient, Amount baseAmount)
      {
         this.Ingredient = ingredient;
         this.Amount = baseAmount;
      }

      public override string ToString()
      {
         if (Ingredient != null && Amount != null)
            return String.Format("{0}: {1}", Ingredient.Name, Amount);

         if (Ingredient != null)
            return Ingredient.Name;

         return String.Empty;
      }

      public virtual IngredientAggregation AddUsage(IngredientUsage ingredient)
      {
         if (ingredient.Ingredient.Id != this.Ingredient.Id)
            throw new ArgumentException("Can only call IngredientAggregation::AddUsage() on original ingredient.");

         //Calculate new total
         if (this.Amount.Unit == ingredient.Amount.Unit || UnitConverter.CanConvert(this.Amount.Unit, ingredient.Amount.Unit)) //Just add
         {
            this.Amount += ingredient.Amount;
         }
         else //Find a conversion path between Ingredient and Form
         {
            var amount = FormConversion.GetNativeAmountForUsage(this.Ingredient, ingredient);
            this.Amount += amount;
         }

         return this; // Allows AddUsage calls to be chained together
      }

      public virtual ShoppingListItem GetItem()
      {
         return new ShoppingListItem(Ingredient)
         {
            Amount = Amount
         };
      }
   }
}


text:
<Page>
  <StackLayout id="stack" backgroundColor="LightGray">
    <Button id="button" text="button" backgroundColor="Green" />
    <Label id="label" text="label"  backgroundColor="Yellow"/>
    <TextField id="textField" text="text-field" hint="hint" backgroundColor="Red"/>
    <TextView id="textView" text="text-view" backgroundColor="Blue"/>
  </StackLayout>
</Page>


text:
#ifndef PROTO_H_
#define PROTO_H_

#ifdef __cplusplus
extern "C" {
#endif

#define ZOO_NOTIFY_OP 0
#define ZOO_CREATE_OP 1
#define ZOO_DELETE_OP 2
#define ZOO_EXISTS_OP 3
#define ZOO_GETDATA_OP 4
#define ZOO_SETDATA_OP 5
#define ZOO_GETACL_OP 6
#define ZOO_SETACL_OP 7
#define ZOO_GETCHILDREN_OP 8
#define ZOO_SYNC_OP 9
#define ZOO_PING_OP 11
#define ZOO_GETCHILDREN2_OP 12
#define ZOO_CHECK_OP 13
#define ZOO_MULTI_OP 14
#define ZOO_CREATE2_OP 15
#define ZOO_RECONFIG_OP 16
#define ZOO_CLOSE_OP -11
#define ZOO_SETAUTH_OP 100
#define ZOO_SETWATCHES_OP 101

#ifdef __cplusplus
}
#endif

#endif /*PROTO_H_*/


text:
package sun.jvm.hotspot.utilities;

/** A class enabling simple construction of type-safe integer
    enumerations */

public class IntegerEnum {
  private int value;

  /** Constructor is protected because it will only be used by the
      subclass */
  protected IntegerEnum(int value) {
    this.value = value;
  }

  public int getValue() {
    return value;
  }
}


text:
PYTHON=python3
command -v $PYTHON &>/dev/null || PYTHON=python

# setup_wiredtiger_cache checks amount of available RAM (it has to use cgroups in container)
# and if there are any memory restrictions set storage.wiredTiger.engineConfig.cacheSizeGB
# in MONGODB_CONFIG_PATH to upstream default size
# it is intended to update mongod.conf.template, with custom config file it might create conflict
function setup_wiredtiger_cache() {
  local config_file
  config_file=${1:-$MONGODB_CONFIG_PATH}

  declare $($PYTHON /usr/libexec/cgroup-limits)
  if [[ ! -v MEMORY_LIMIT_IN_BYTES || "${NO_MEMORY_LIMIT:-}" == "true" ]]; then
    return 0;
  fi

  cache_size=$($PYTHON -c "min=1; limit=int(($MEMORY_LIMIT_IN_BYTES / pow(2,30) - 1) * 0.6); print( min if limit < min else limit)")
  echo "storage.wiredTiger.engineConfig.cacheSizeGB: ${cache_size}" >> ${config_file}

  info "wiredTiger cacheSizeGB set to ${cache_size}"
}

setup_wiredtiger_cache ${CONTAINER_SCRIPTS_PATH}/mongod.conf.template


text:
(function($){

rocket.subview.howtoindex_content = rocket.subview.extend({

    el: '#howtoindex_page_content'

    ,template: _.template($('#template_howtoindex_articles').text())

    ,init: function(options){
        var me = this;

        // @note: 标识是否第一次加载,避免后续多次加载
        me.isFirstLoad = true;

        me.collection = new rocket.collection.howtoindex_articles(
            null
            ,$.extend({}, options)
        );

        // 显示页面loading
        me.showLoading(me.$el);
    }

    // @note: 若不涉及回收,可以不提供unregisterEvents
    ,registerEvents: function(){
        var me = this, ec = me.ec;

        ec.on("pagebeforechange", me.onpagebeforechange, me);

        // collection的reset事件,model的change事件
        me.collection.on('reset', me.render, me);
    }

    ,render: function(){
        var me = this,
            jianjie_tag = '简介',
            basics_tag = '基础',
            rumen_tag = '入门',
            standards_tag = '规范',
            workshop_tag = 'workshop',
            jinjie_tag = '进阶';

        me.$el.append(me.template({
            jianjie_tag: jianjie_tag
            ,jianjie_articles: me.collection.getByTag(jianjie_tag)

            ,basics_tag: basics_tag
            ,basics_articles: me.collection.getByTag(basics_tag)

            ,workshop_tag: workshop_tag
            ,workshop_articles: me.collection.getByTag(workshop_tag)

            ,rumen_tag: rumen_tag
            ,rumen_articles: me.collection.getByTag(rumen_tag)

            ,standards_tag: standards_tag
            ,standards_articles: me.collection.getByTag(standards_tag)

            ,jinjie_tag: jinjie_tag
            ,jinjie_articles: me.collection.getByTag(jinjie_tag)
        }));

        me.hideLoading();
    }

    ,onpagebeforechange: function(params){
        var me = this,
            from = params.from,
            to = params.to,
            param = params.params;

        if(to == me.ec) {
            if(me.isFirstLoad){
                me.collection.fetch({
                    reset: true
                    ,success: function(){
                        me.isFirstLoad = false;
                    }
                });
            }
            me.$el.show();
        }
    }

});

})(Zepto);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>prosa: Error</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / extra-dev

dev / prosa - dev

            « Up

              prosa

                dev
                Error

 (2021-10-27 02:59:51 UTC)

Context

# Packages matching: installed
# Name                # Installed # Synopsis
base-bigarray         base
base-threads          base
base-unix             base
conf-findutils        1           Virtual package relying on findutils
conf-gmp              3           Virtual package relying on a GMP lib system installation
coq                   dev         Formal proof management system
dune                  2.9.1       Fast, portable, and opinionated build system
ocaml                 4.12.0      The OCaml compiler (virtual package)
ocaml-base-compiler   4.12.0      Official release 4.12.0
ocaml-config          2           OCaml Switch Configuration
ocaml-options-vanilla 1           Ensure that OCaml is compiled with no special options enabled
ocamlfind             1.9.1       A library manager for OCaml
zarith                1.12        Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Pierre Roux <pierre.roux@onera.fr>"
homepage: "https://prosa.mpi-sws.org/"
dev-repo: "git+https://gitlab.mpi-sws.org/RT-PROOFS/rt-proofs.git"
bug-reports: "https://gitlab.mpi-sws.org/RT-PROOFS/rt-proofs/issues"
license: "BSD"
build: [
  ["./create_makefile.sh"]
  [make "-j%{jobs}%"]
]
install: [make "install"]
depends: [
  "coq" {((>= "8.11" & < "8.13~") | = "dev")}
  "coq-mathcomp-ssreflect" {((>= "1.10" & < "1.12~") | = "dev")}
]
tags: [
  "keyword:prosa"
  "keyword:real time"
  "keyword:schedulability analysis"
  "logpath:prosa"
]
authors: [
  "Felipe Cerqueira"
  "Björn Brandenburg"
  "Maxime Lesourd"
  "Sergey Bozhko"
  "Xiaojie Guo"
  "Sophie Quinton"
  "Marco Perronet"
]
synopsis: "A Foundation for Formally Proven Schedulability Analysis"
description: """Prosa is a repository of definitions and proofs for
real-time schedulability analysis built with Coq. Prosa's
distinguishing characteristic is that Prosa prioritizes readability
over all other concerns to ensure that specifications remain
accessible to readers without a background in formal proofs. (A
background in real-time scheduling is assumed.)"""
url {
  src: "git+https://gitlab.mpi-sws.org/RT-PROOFS/rt-proofs.git"
}

Lint

Command

true

Return code

0

Dry install

Dry install with the current Coq version:

Command

opam install -y --show-action coq-prosa.dev coq.dev

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-prosa.dev coq.dev

Return code

0

Duration

2 m 7 s

Install

Command

opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y coq-prosa.dev coq.dev

Return code

7936

Duration

1 m 36 s

Output

# Packages matching: installed
# Name                 # Installed # Synopsis
base-bigarray          base
base-threads           base
base-unix              base
conf-findutils         1           Virtual package relying on findutils
conf-gmp               3           Virtual package relying on a GMP lib system installation
coq                    dev         Formal proof management system
coq-mathcomp-ssreflect dev         Small Scale Reflection
dune                   2.9.1       Fast, portable, and opinionated build system
ocaml                  4.12.0      The OCaml compiler (virtual package)
ocaml-base-compiler    4.12.0      Official release 4.12.0
ocaml-config           2           OCaml Switch Configuration
ocaml-options-vanilla  1           Ensure that OCaml is compiled with no special options enabled
ocamlfind              1.9.1       A library manager for OCaml
zarith                 1.12        Implements arithmetic and logical operations over arbitrary-precision integers
[NOTE] Package coq is already installed (current version is dev).
The following actions will be performed:
  - install coq-prosa dev
<><> Gathering sources ><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
[coq-prosa.dev] synchronised from git+https://gitlab.mpi-sws.org/RT-PROOFS/rt-proofs.git
<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><>
[ERROR] The compilation of coq-prosa failed at "/home/bench/.opam/opam-init/hooks/sandbox.sh build make -j4".
#=== ERROR while compiling coq-prosa.dev ======================================#
# context              2.0.8 | linux/x86_64 | ocaml-base-compiler.4.12.0 | file:///home/bench/run/opam-coq-archive/extra-dev
# path                 ~/.opam/ocaml-base-compiler.4.12.0/.opam-switch/build/coq-prosa.dev
# command              ~/.opam/opam-init/hooks/sandbox.sh build make -j4
# exit-code            2
# env-file             ~/.opam/log/coq-prosa-29217-0a5907.env
# output-file          ~/.opam/log/coq-prosa-29217-0a5907.out
### output ###
# Error: No such bound variable l0 (possible names are: rel, F, l, x and y).
# [...]
# make[1]: *** [Makefile:787: classic/util/minmax.vo] Error 1
# make[1]: *** Waiting for unfinished jobs....
# File "./model/task/absolute_deadline.v", line 8, characters 0-226:
# Warning: The default value for instance locality is currently "local" in a
# section and "global" otherwise, but is scheduled to change in a future
# release. For the time being, adding instances outside of sections without
# specifying an explicit locality attribute is therefore deprecated. It is
# recommended to use "export" whenever possible. Use the attributes #[local],
# #[global] and #[export] depending on your choice. For example: "#[export]
# Instance Foo : Bar := baz." [deprecated-instance-without-locality,deprecated]
# make: *** [Makefile:392: all] Error 2
<><> Error report <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
+- The following actions failed
| - build coq-prosa dev
+-
- No changes have been performed
# Run eval $(opam env) to update the current shell environment

Installation size

No files were installed.

Uninstall

Command

true

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub. © Guillaume Claret.


text:
package com.srmhackathon.haasil;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private String TAG = "RISABH";

 ViewPager viewPager;
    MenuItem prevMenuItem;
    BottomNavigationView navigation;
    foodFrag fFrag;
    elecFrag eFrag;
    wasteFrag wFrag;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_waste:
                    viewPager.setCurrentItem(0);
                    return true;
                case R.id.navigation_food:
                    viewPager.setCurrentItem(1);
                    return true;
                case R.id.navigation_elec:
                    viewPager.setCurrentItem(2);
                    return true;
            }
            return false;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth=FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
                // ...
            }
        };

 		viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseUser currentUser=mAuth.getCurrentUser();
        if(currentUser==null)
            startActivity(new Intent(this,Login.class));
        mAuth.addAuthStateListener(mAuthListener);

    }

      private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        fFrag = new foodFrag();
        eFrag = new elecFrag();
        wFrag = new wasteFrag();

        adapter.addFragment(wFrag);
        adapter.addFragment(fFrag);
        adapter.addFragment(eFrag);

        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (prevMenuItem != null) {
                    prevMenuItem.setChecked(false);
                } else {
                    navigation.getMenu().getItem(0).setChecked(false);
                }

                navigation.getMenu().getItem(position).setChecked(true);
                prevMenuItem = navigation.getMenu().getItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

}


text:
package com.google.cloud.spanner.it;

import static com.google.cloud.spanner.testing.EmulatorSpannerHelper.isUsingEmulator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;

import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Dialect;
import com.google.cloud.spanner.IntegrationTestEnv;
import com.google.cloud.spanner.ParallelIntegrationTest;
import com.google.cloud.spanner.testing.RemoteSpannerHelper;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.StreamSupport;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

/** Dialect aware integration tests for {@link com.google.cloud.spanner.DatabaseAdminClient}. */
@Category(ParallelIntegrationTest.class)
@RunWith(Parameterized.class)
public class ITDatabaseAdminDialectAwareTest {

  @ClassRule public static IntegrationTestEnv env = new IntegrationTestEnv();
  private static final Duration OPERATION_TIMEOUT = Duration.ofMinutes(20);
  private DatabaseAdminClient client;
  private RemoteSpannerHelper testHelper;
  private List<DatabaseId> databases;

  @Parameter public Dialect dialect;

  @Parameters(name = "dialect = {0}")
  public static Object[] data() {
    return Dialect.values();
  }

  @Before
  public void setUp() {
    testHelper = env.getTestHelper();
    client = testHelper.getClient().getDatabaseAdminClient();
    databases = new ArrayList<>();
  }

  @After
  public void tearDown() {
    if (databases != null) {
      for (DatabaseId id : databases) {
        try {
          client.dropDatabase(id.getInstanceId().getInstance(), id.getDatabase());
        } catch (Exception e) {
          System.err.println("Could not drop database " + id + ", skipping...: " + e.getMessage());
        }
      }
    }
  }

  @Test
  public void testCreateDatabaseWithDialect() throws Exception {
    assumeFalse("emulator does not support different dialects", isUsingEmulator());

    final String projectId = testHelper.getInstanceId().getProject();
    final String instanceId = testHelper.getInstanceId().getInstance();
    final String databaseId = testHelper.getUniqueDatabaseId();

    final Database databaseToCreate =
        client
            .newDatabaseBuilder(DatabaseId.of(projectId, instanceId, databaseId))
            .setDialect(dialect)
            .build();
    databases.add(databaseToCreate.getId());

    // Creates the database with the dialect set
    final Database createdDatabase =
        client
            .createDatabase(databaseToCreate, Collections.emptyList())
            .get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
    assertEquals(dialect, createdDatabase.getDialect());

    // Test dialect in database retrieval
    final Database retrievedDatabase = client.getDatabase(instanceId, databaseId);
    assertEquals(dialect, retrievedDatabase.getDialect());

    // Test dialect database listing
    final Optional<Database> maybeListedDatabase =
        StreamSupport.stream(client.listDatabases(instanceId).iterateAll().spliterator(), false)
            .filter(database -> database.getId().getDatabase().equals(databaseId))
            .findFirst();
    assertTrue("Expected to find database in list", maybeListedDatabase.isPresent());
    assertEquals(dialect, maybeListedDatabase.get().getDialect());
  }
}


text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * helpers.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Payment;

/**
 * Generate a signature.
 *
 * @param array  $attributes
 * @param string $key
 * @param string $encryptMethod
 *
 * @return string
 */
function generate_sign(array $attributes, $key, $encryptMethod = 'md5')
{
    ksort($attributes);

    $attributes['key'] = $key;

    return strtoupper(call_user_func_array($encryptMethod, [urldecode(http_build_query($attributes))]));
}

/**
 * Get client ip.
 *
 * @return string
 */
function get_client_ip()
{
    if (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    } else {
        // for php-cli(phpunit etc.)
        $ip = defined('PHPUNIT_RUNNING') ? '127.0.0.1' : gethostbyname(gethostname());
    }

    return filter_var($ip, FILTER_VALIDATE_IP) ?: '127.0.0.1';
}

/**
 * Get current server ip.
 *
 * @return string
 */
function get_server_ip()
{
    if (!empty($_SERVER['SERVER_ADDR'])) {
        $ip = $_SERVER['SERVER_ADDR'];
    } elseif (!empty($_SERVER['SERVER_NAME'])) {
        $ip = gethostbyname($_SERVER['SERVER_NAME']);
    } else {
        // for php-cli(phpunit etc.)
        $ip = defined('PHPUNIT_RUNNING') ? '127.0.0.1' : gethostbyname(gethostname());
    }

    return filter_var($ip, FILTER_VALIDATE_IP) ?: '127.0.0.1';
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef _NSKEYGENHANDLER_H_
#define _NSKEYGENHANDLER_H_
// Form Processor
#include "nsIFormProcessor.h"
#include "nsTArray.h"

nsresult GetSlotWithMechanism(uint32_t mechanism,
                              nsIInterfaceRequestor *ctx,
                              PK11SlotInfo **retSlot);

#define DEFAULT_RSA_KEYGEN_PE 65537L
#define DEFAULT_RSA_KEYGEN_ALG SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION

SECKEYECParams *decode_ec_params(const char *curve);

class nsKeygenFormProcessor : public nsIFormProcessor {
public:
  nsKeygenFormProcessor();
  virtual ~nsKeygenFormProcessor();
  nsresult Init();

  NS_IMETHOD ProcessValue(nsIDOMHTMLElement *aElement,
                          const nsAString& aName,
                          nsAString& aValue);

  NS_IMETHOD ProvideContent(const nsAString& aFormType,
                            nsTArray<nsString>& aContent,
                            nsAString& aAttribute);
  NS_DECL_THREADSAFE_ISUPPORTS

  static nsresult Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);

protected:
  nsresult GetPublicKey(nsAString& aValue, nsAString& aChallenge,
			nsAFlatString& akeyType, nsAString& aOutPublicKey,
			nsAString& aPqg);
  nsresult GetSlot(uint32_t aMechanism, PK11SlotInfo** aSlot);
private:
  nsCOMPtr<nsIInterfaceRequestor> m_ctx;

  typedef struct SECKeySizeChoiceInfoStr {
      nsString name;
      int size;
  } SECKeySizeChoiceInfo;

  enum { number_of_key_size_choices = 2 };

  SECKeySizeChoiceInfo mSECKeySizeChoiceList[number_of_key_size_choices];
};

#endif //_NSKEYGENHANDLER_H_


text:
<?php
/**
 * 用例
 */

namespace LanguageStatement\DesignModel\DesignMethod\MVC;
spl_autoload_register(function($className){
    $filePath=__DIR__.'/../../../../'.$className.'.php';
    if(file_exists($filePath)){
        require_once $filePath;
    }
});

$user=new UserModel('goodName');
$controller=new UserController();
$view=new View();
$view->showUser($controller,$user);


text:
module Pano
  class GuideController < ApplicationController

    def index
      # The home page
    end

    def css
      # CSS
    end

    def js
      # Javascript
    end

    def helpers
      # Rails Helpers
    end

  end
end


text:
@interface HITPeriodicPlugin ()
@property NSNumber *repeat;
@property NSTimer *cron;
@end

@implementation HITPeriodicPlugin

- (instancetype)initWithSettings:(NSDictionary *)settings
{
    self = [super initWithSettings:settings];
    if (self) {
        _repeat = [settings objectForKey:kHITPeriodicPluginRepeatKey];

        if ([_repeat intValue] > 0) {
            [self performSelector:@selector(setupCronJob)
                       withObject:nil
                       afterDelay:0];
        }
    }
    return self;
}

- (void)setupCronJob {
    _cron = [NSTimer scheduledTimerWithTimeInterval:[_repeat integerValue]
                                             target:self
                                           selector:@selector(periodicAction:)
                                           userInfo:nil
                                            repeats:YES];

    [_cron fire];
}

@end


text:
import React from 'react';
import { Router, browserHistory } from 'react-router';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import routes from './routes';
import store from './store/configureStore';
import './static/styles/style.scss';
import './static/styles/toastr.scss';
import '../node_modules/sweetalert/dist/sweetalert.css';

// window.clientStore = store;
render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>,
  document.getElementById('app')
);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Problem_01___Book_Problem
{
    class Program
    {
        static void Main(string[] args)
        {
            //60 min.
            double pages = int.Parse(Console.ReadLine());
            double daysOff = int.Parse(Console.ReadLine());
            double normalRead = int.Parse(Console.ReadLine());

            double daysRead = 30 - daysOff;

            if (daysRead<=0)
            {
                Console.WriteLine("never");
            }
            else
            {
                double mounthOfReads = (pages / (daysRead*normalRead));

                double years = Math.Floor((mounthOfReads)/12);
                double mounths = Math.Ceiling((mounthOfReads-(years*12)));

                Console.WriteLine("{0} years {1} months", years, mounths);
            }
        }
    }
}


text:
<!doctype html>

		<title>Zabuun - Learn Arabic for English Speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

						Modern Standard Arabic (MSA) | Egyptian Colloquial Arabic (ECA) | Both

Daily Life

How about a Pizza?

  A: What's for dinner?
 B: I'm not sure.
 A: How about a pizza?
 B: You had pizza for lunch.
 A: But I love pizza.
 B: Everybody loves pizza.
 A: So why can't I have pizza for dinner?
 B: Because you need variety.
 A: What's "variety?
 B: Different things—not the same thing all the time

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
#include <stdlib.h>
#include <string.h>
#include "soc/cpu.h"
#include "FreeRTOS.h"
#include "task.h"
#include "esp_intr_alloc.h"
#include "esp_err.h"
#include "esp_log.h"
#include "sdkconfig.h"
#ifdef CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER
#include "soc/periph_defs.h"
#include "soc/system_reg.h"
#include "hal/systimer_hal.h"
#include "hal/systimer_ll.h"
#endif

#ifdef CONFIG_PM_TRACE
#include "esp_private/pm_trace.h"
#endif //CONFIG_PM_TRACE

BaseType_t xPortSysTickHandler(void);

#ifdef CONFIG_FREERTOS_SYSTICK_USES_CCOUNT
extern void _frxt_tick_timer_init(void);
extern void _xt_tick_divisor_init(void);

#ifdef CONFIG_FREERTOS_CORETIMER_0
    #define SYSTICK_INTR_ID (ETS_INTERNAL_TIMER0_INTR_SOURCE+ETS_INTERNAL_INTR_SOURCE_OFF)
#endif
#ifdef CONFIG_FREERTOS_CORETIMER_1
    #define SYSTICK_INTR_ID (ETS_INTERNAL_TIMER1_INTR_SOURCE+ETS_INTERNAL_INTR_SOURCE_OFF)
#endif

/**
 * @brief Initialize CCONT timer to generate the tick interrupt
 *
 */
void vPortSetupTimer(void)
{
    /* Init the tick divisor value */
    _xt_tick_divisor_init();

    _frxt_tick_timer_init();
}

#elif CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER

_Static_assert(SOC_CPU_CORES_NUM <= SOC_SYSTIMER_ALARM_NUM - 1, "the number of cores must match the number of core alarms in SYSTIMER");

void SysTickIsrHandler(void *arg);

static uint32_t s_handled_systicks[portNUM_PROCESSORS] = { 0 };

#define SYSTICK_INTR_ID (ETS_SYSTIMER_TARGET0_EDGE_INTR_SOURCE)

/**
 * @brief Set up the systimer peripheral to generate the tick interrupt
 *
 * Both timer alarms are configured in periodic mode.
 * It is done at the same time so SysTicks for both CPUs occur at the same time or very close.
 * Shifts a time of triggering interrupts for core 0 and core 1.
 */
void vPortSetupTimer(void)
{
    unsigned cpuid = xPortGetCoreID();
#ifdef CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3
    const unsigned level = ESP_INTR_FLAG_LEVEL3;
#else
    const unsigned level = ESP_INTR_FLAG_LEVEL1;
#endif
    /* Systimer HAL layer object */
    static systimer_hal_context_t systimer_hal;
    /* set system timer interrupt vector */
    ESP_ERROR_CHECK(esp_intr_alloc(ETS_SYSTIMER_TARGET0_EDGE_INTR_SOURCE + cpuid, ESP_INTR_FLAG_IRAM | level, SysTickIsrHandler, &systimer_hal, NULL));

    if (cpuid == 0) {
        systimer_hal_init(&systimer_hal);
        systimer_ll_set_counter_value(systimer_hal.dev, SYSTIMER_LL_COUNTER_OS_TICK, 0);
        systimer_ll_apply_counter_value(systimer_hal.dev, SYSTIMER_LL_COUNTER_OS_TICK);

        for (cpuid = 0; cpuid < SOC_CPU_CORES_NUM; cpuid++) {
            systimer_hal_counter_can_stall_by_cpu(&systimer_hal, SYSTIMER_LL_COUNTER_OS_TICK, cpuid, false);
        }

        for (cpuid = 0; cpuid < portNUM_PROCESSORS; ++cpuid) {
            uint32_t alarm_id = SYSTIMER_LL_ALARM_OS_TICK_CORE0 + cpuid;

            /* configure the timer */
            systimer_hal_connect_alarm_counter(&systimer_hal, alarm_id, SYSTIMER_LL_COUNTER_OS_TICK);
            systimer_hal_set_alarm_period(&systimer_hal, alarm_id, 1000000UL / CONFIG_FREERTOS_HZ);
            systimer_hal_select_alarm_mode(&systimer_hal, alarm_id, SYSTIMER_ALARM_MODE_PERIOD);
            systimer_hal_counter_can_stall_by_cpu(&systimer_hal, SYSTIMER_LL_COUNTER_OS_TICK, cpuid, true);
            if (cpuid == 0) {
                systimer_hal_enable_alarm_int(&systimer_hal, alarm_id);
                systimer_hal_enable_counter(&systimer_hal, SYSTIMER_LL_COUNTER_OS_TICK);
#ifndef CONFIG_FREERTOS_UNICORE
                // SysTick of core 0 and core 1 are shifted by half of period
                systimer_hal_counter_value_advance(&systimer_hal, SYSTIMER_LL_COUNTER_OS_TICK, 1000000UL / CONFIG_FREERTOS_HZ / 2);
#endif
            }
        }
    } else {
        uint32_t alarm_id = SYSTIMER_LL_ALARM_OS_TICK_CORE0 + cpuid;
        systimer_hal_enable_alarm_int(&systimer_hal, alarm_id);
    }
}

/**
 * @brief Systimer interrupt handler.
 *
 * The Systimer interrupt for SysTick works in periodic mode no need to calc the next alarm.
 * If a timer interrupt is ever serviced more than one tick late, it is necessary to process multiple ticks.
 */
IRAM_ATTR void SysTickIsrHandler(void *arg)
{
    uint32_t cpuid = xPortGetCoreID();
    systimer_hal_context_t *systimer_hal = (systimer_hal_context_t *)arg;
#ifdef CONFIG_PM_TRACE
    ESP_PM_TRACE_ENTER(TICK, cpuid);
#endif

    uint32_t alarm_id = SYSTIMER_LL_ALARM_OS_TICK_CORE0 + cpuid;
    do {
        systimer_ll_clear_alarm_int(systimer_hal->dev, alarm_id);

        uint32_t diff = systimer_hal_get_counter_value(systimer_hal, SYSTIMER_LL_COUNTER_OS_TICK) / systimer_ll_get_alarm_period(systimer_hal->dev, alarm_id) - s_handled_systicks[cpuid];
        if (diff > 0) {
            if (s_handled_systicks[cpuid] == 0) {
                s_handled_systicks[cpuid] = diff;
                diff = 1;
            } else {
                s_handled_systicks[cpuid] += diff;
            }

            do {
                xPortSysTickHandler();
            } while (--diff);
        }
    } while (systimer_ll_is_alarm_int_fired(systimer_hal->dev, alarm_id));

#ifdef CONFIG_PM_TRACE
    ESP_PM_TRACE_EXIT(TICK, cpuid);
#endif
}

#endif // CONFIG_FREERTOS_SYSTICK_USES_CCOUNT

/**
 * @brief Handler of SysTick
 *
 * The function is called from:
 *  - _frxt_timer_int for xtensa with CONFIG_FREERTOS_SYSTICK_USES_CCOUNT
 *  - SysTickIsrHandler for xtensa with CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER
 *  - SysTickIsrHandler for riscv
 */
BaseType_t xPortSysTickHandler(void)
{
    portbenchmarkIntLatency();
    traceISR_ENTER(SYSTICK_INTR_ID);
    BaseType_t ret = xTaskIncrementTick();
    if(ret != pdFALSE) {
        portYIELD_FROM_ISR();
    } else {
        traceISR_EXIT();
    }
    return ret;
}


text:
using System;
using System.ComponentModel;

namespace Chapter07
{
    [Description("Listing 7.04")]
    public static class StaticStringHelper
    {
        public static string Reverse(string input)
        {
            char[] chars = input.ToCharArray();
            Array.Reverse(chars);
            return new string(chars);
        }
    }
}


text:
<!doctype html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>GwtQuery: ${projectName} plugin example</title>

Hello world