text:
id: 5a24bbe0dba28a8d3cbd4c5f
title: Render HTML Elements to the DOM
challengeType: 6
isRequired: false
videoUrl: ''
localeTitle: تقديم عناصر HTML إلى DOM
---

## Description

 حتى الآن ، تعلمت أن JSX هي أداة ملائمة لكتابة HTML قابل للقراءة في JavaScript. باستخدام React ، يمكننا تقديم JSX مباشرةً إلى HTML DOM باستخدام واجهة برمجة تطبيقات React التي تُعرف باسم ReactDOM. يقدم ReactDOM طريقة بسيطة لعرض عناصر ReactDOM.render(componentToRender, targetNode) DOM التي تبدو كما يلي: ReactDOM.render(componentToRender, targetNode) ، حيث تكون الوسيطة الأولى هي عنصر React أو المكون الذي تريد ReactDOM.render(componentToRender, targetNode) الثانية هي عقدة DOM التي تريد تقديم المكون إليها. كما هو متوقع ، يجب استدعاء ReactDOM.render() بعد تعريفات عناصر JSX ، تمامًا كما يجب أن تقوم بتعريف المتغيرات قبل استخدامها.

## Instructions

 يحتوي محرر التعليمة البرمجية على مكون JSX بسيط. استخدم الأسلوب ReactDOM.render() لتقديم هذا المكون إلى الصفحة. يمكنك تمرير عناصر JSX المحددة مباشرة كوسيطة أولى واستخدام document.getElementById() لتحديد عقدة DOM لتقديمها. يوجد div به id='challenge-node' متاح للاستخدام. تأكد من عدم تغيير ثابت JSX .

## Tests

```yml
tests:
  - text: يجب على <code>JSX</code> المستمر إرجاع عنصر <code>div</code> .
    testString: 'assert(JSX.type === "div", "The constant <code>JSX</code> should return a <code>div</code> element.");'
  - text: يجب أن يحتوي <code>div</code> على علامة <code>h1</code> باعتبارها العنصر الأول.
    testString: 'assert(JSX.props.children[0].type === "h1", "The <code>div</code> should contain an <code>h1</code> tag as the first element.");'
  - text: يجب أن يحتوي <code>div</code> على علامة <code>p</code> كعنصر ثانٍ.
    testString: 'assert(JSX.props.children[1].type === "p", "The <code>div</code> should contain a <code>p</code> tag as the second element.");'
  - text: يجب أن يتم تقديم عنصر JSX المقدم إلى عقدة DOM مع عقدة <code>challenge-node</code> الهوية.
    testString: 'assert(document.getElementById("challenge-node").childNodes[0].innerHTML === "<h1>Hello World</h1><p>Lets render this to the DOM</p>", "The provided JSX element should render to the DOM node with id <code>challenge-node</code>.");'

```

## Challenge Seed

```jsx
const JSX = (
  <div>
    <h1>Hello World</h1>
    <p>Lets render this to the DOM</p>
  </div>
);
// change code below this line

```

## Solution

```js
// solution required
```


text:
package io.doov.core.serial.adapter;

import io.doov.core.FieldInfo;
import io.doov.core.serial.TypeAdapter;

public class StringTypeAdapter implements TypeAdapter {

    @Override
    public boolean accept(FieldInfo info) {
        return String.class.equals(info.type());
    }

    @Override
    public boolean accept(Object value) {
        return value instanceof String;
    }

    @Override
    public String toString(Object value) {
        return value.toString();
    }

    @Override
    public Object fromString(FieldInfo info, String value) {
        return value;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package net.folab.metaj.jast;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.MethodVisitor;

import net.folab.metaj.bytecode.Java;
import net.folab.metaj.bytecode.JavaType;
import net.folab.metaj.bytecode.StatementContext;

public class AstWriter implements AstVisitor, Opcodes {

    private final Java java;

    private final ClassWriter cv;

    public AstWriter(Java java) {
        this.java = java;
        this.cv = new ClassWriter(false);
    }

    @Override
    public void visitClass(ClassDeclaration cd) {

        String[] interfaces = new String[cd.interfaces.length];
        for (int i = 0; i < interfaces.length; i++) {
            interfaces[i] = cd.interfaces[i].getName();
        }

        cv.visit(java.version, // version
                cd.accessModifier.modifier, // access
                cd.name, // name
                null, // signature
                cd.superClass.getName(), // superName
                interfaces // interfaces
        );

        // TODO detect constructor of super class
        new MethodDeclaration(cd, "<init>") //
                .setParameterTypes() //
                .setReturnType(JavaType.VOID) //
                .addStatement( //
                        new ConstructorInvocation( //
                                "java/lang/Object", //
                                "()V", //
                                new LocalVariable("this") //
                        ) //
                ) //
                .addStatement(Return.VOID) //
                .accept(this);

        for (MemberDeclaration md : cd.mds) {
            if (md instanceof MethodDeclaration) {
                MethodDeclaration mm = (MethodDeclaration) md;
                mm.accept(this);
            }
        }

        cv.visitEnd();

    }

    @Override
    public void visitField(FieldDeclaration md) {
        String desc = md.type.getDescName();

        int modifier = md.access.modifier;
//        if (md.isStatic)
//            modifier += ACC_STATIC;
        cv.visitField(modifier, // access
                md.name, // name
                desc, // desc
                null, // signature
                null // value
        );

    }

    @Override
    public void visitMethod(MethodDeclaration md) {

        String desc = "(";
        for (JavaType pt : md.parameterTypes) {
            desc += pt.getDescName();
        }
        desc += ")";
        desc += md.returnType.getDescName();

        int modifier = md.access.modifier;
        if (md.block.isStatic)
            modifier += ACC_STATIC;
        MethodVisitor mv = cv.visitMethod(//
                modifier, // access
                md.name, // name
                desc, // desc
                null, // signature
                null // exceptions
                );

        mv.visitCode();

        StatementContext ctx = new StatementContext();

        if (!md.block.isStatic) {
            ctx.addLocal("this", new JavaType(md.cd.name));
        }

        for (Statement statement : md.block.statements) {
            statement.generate(mv, ctx);
        }

        mv.visitMaxs(ctx.maxStack(), ctx.maxLocals());
        mv.visitEnd();

    }

    @Override
    public byte[] toByteArray() {
        return cv.toByteArray();
    }

}


text:
import unittest

from os.path import dirname, join

from mycroft.configuration import ConfigurationLoader, ConfigurationManager, \
    DEFAULT_CONFIG, SYSTEM_CONFIG, USER_CONFIG, RemoteConfiguration

class AbstractConfigurationTest(unittest.TestCase):
    def setUp(self):
        self.config_path = join(dirname(__file__), 'mycroft.conf')

    @staticmethod
    def create_config(lang='en-us', module='mimic', voice="ap"):
        config = {
            'lang': lang,
            'tts': {
                'module': module,
                module: {'voice': voice}
            }
        }
        return config

    def assert_config(self, config, lang='en-us', module='mimic', voice="ap"):
        self.assertIsNotNone(config)
        lan = config.get('lang')
        self.assertIsNotNone(lan)
        self.assertEquals(lan, lang)
        tts = config.get('tts')
        self.assertIsNotNone(tts)
        mod = tts.get('module')
        self.assertEquals(mod, module)
        voi = tts.get(mod, {}).get("voice")
        self.assertEquals(voi, voice)

class ConfigurationLoaderTest(AbstractConfigurationTest):
    def test_init_config_with_defaults(self):
        self.assertEquals(ConfigurationLoader.init_config(), {})

    def test_init_config_with_new_config(self):
        config = {'a': 'b'}
        self.assertEquals(ConfigurationLoader.init_config(config), config)

    def test_init_locations_with_defaults(self):
        locations = [DEFAULT_CONFIG, SYSTEM_CONFIG, USER_CONFIG]
        self.assertEquals(ConfigurationLoader.init_locations(), locations)

    def test_init_locations_with_new_location(self):
        locations = [self.config_path]
        self.assertEquals(ConfigurationLoader.init_locations(locations),
                          locations)

    def test_validate_data(self):
        try:
            ConfigurationLoader.validate({}, [])
        except TypeError:
            self.fail()

    def test_validate_data_with_invalid_data(self):
        self.assertRaises(TypeError, ConfigurationLoader.validate)

    def test_load(self):
        self.assert_config(ConfigurationLoader.load())

    def test_load_with_override_custom(self):
        config = self.create_config('pt-br', 'espeak', 'f1')
        config = ConfigurationLoader.load(config)
        self.assert_config(config)

    def test_load_with_override_default(self):
        config = self.create_config()
        config = ConfigurationLoader.load(config, [self.config_path])
        self.assert_config(config, 'pt-br', 'espeak', 'f1')

    def test_load_with_extra_custom(self):
        my_config = {'key': 'value'}
        config = ConfigurationLoader.load(my_config)
        self.assert_config(config)

        value = config.get('key', None)
        self.assertIsNotNone(value)
        self.assertEquals(value, my_config.get('key'))

    def test_load_with_invalid_config_type(self):
        self.assertRaises(TypeError, ConfigurationLoader.load, 'invalid_type')

    def test_load_with_invalid_locations_type(self):
        self.assertRaises(TypeError, ConfigurationLoader.load,
                          None, self.config_path)

    def test_load_with_invalid_locations_path(self):
        locations = ['./invalid/mycroft.conf', './invalid_mycroft.conf']
        config = ConfigurationLoader.load(None, locations, False)
        self.assertEquals(config, {})

@unittest.skip('Disabled while unittests are brought upto date')
class RemoteConfigurationTest(AbstractConfigurationTest):
    def test_validate_config(self):
        try:
            RemoteConfiguration.validate(self.create_config())
        except TypeError:
            self.fail()

    def test_validate_config_with_invalid_config(self):
        self.assertRaises(TypeError, RemoteConfiguration.validate)

    def test_load_without_remote_config(self):
        config = self.create_config()
        self.assertEquals(RemoteConfiguration.load(config), config)

class ConfigurationManagerTest(AbstractConfigurationTest):
    def test_load_defaults(self):
        ConfigurationManager.load_defaults()
        self.assert_config(ConfigurationManager.load_defaults())

    def test_load_local(self):
        ConfigurationManager.load_defaults()
        self.assert_config(ConfigurationManager.load_local())

    def test_load_local_with_locations(self):
        ConfigurationManager.load_defaults()
        config = ConfigurationManager.load_local([self.config_path])
        self.assert_config(config, 'pt-br', 'espeak', 'f1')

    def test_load_remote(self):
        ConfigurationManager.load_defaults()
        self.assert_config(ConfigurationManager.load_remote())

    def test_get(self):
        ConfigurationManager.load_defaults()
        self.assert_config(ConfigurationManager.get())

    def test_load_get_with_locations(self):
        ConfigurationManager.load_defaults()
        config = ConfigurationManager.get([self.config_path])
        self.assert_config(config, 'pt-br', 'espeak', 'f1')


text:
require 'test_helper'

class TestToriBackendChain < Test::Unit::TestCase
  include Tori::Backend

  setup do
    @filesystem1 = FileSystem.new(Pathname("test/tmp/tori/store1"))
    File.open(@filesystem1.root.join("testfile-1"), 'w+'){ |f| f.write("text-1") }

    @filesystem2 = FileSystem.new(Pathname("test/tmp/tori/store2"))
    File.open(@filesystem2.root.join("testfile-2"), 'w+'){ |f| f.write("text-2") }

    @backend = Chain.new(@filesystem1, @filesystem2)
  end

  test "#initialize" do
    assert { Chain === Chain.new }
    assert { [@filesystem1, @filesystem2] === Chain.new(@filesystem1, @filesystem2).backends }
    assert { Chain === @filesystem1.otherwise(@filesystem2) }
  end

  test "#backend" do
    assert { @filesystem1 == @backend.backend("testfile-1") }
    assert { @filesystem2 == @backend.backend("testfile-2") }
    assert_raise(Chain::ExistError) { @backend.backend("testfile-3") }
  end

  test "#exist?" do
    assert { true == @backend.exist?("testfile-1") }
    assert { true == @backend.exist?("testfile-2") }
    assert { false == @backend.exist?("testfile-3") }
  end

  test "read" do
    assert { "text-1" == @backend.read("testfile-1") }
    assert { "text-2" == @backend.read("testfile-2") }
    assert_raise(Chain::ExistError) { @backend.read("testfile-3") }
  end

  test "open" do
    @backend.open("testfile-1") do |f|
      assert { "text-1" == f.read }
      assert { "test/tmp/tori/store1/testfile-1" == f.path }
    end
    @backend.open("testfile-2") do |f|
      assert { "text-2" == f.read }
      assert { "test/tmp/tori/store2/testfile-2" == f.path }
    end
    assert_raise(Chain::ExistError) { @backend.read("testfile-3") }
  end
end


text:
package de.nava.demo.repository;

import com.mongodb.MongoClient;
import org.bson.Document;
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * Simplest possible implementation for accessing the MongoDB
 * to persist job history documents.
 *
 * @author Niko Schmuck
 */
@Repository
public class JobHistoryRepository {

    @Autowired
    private MongoClient mongo;

    public void add(Map<String, Object> keys) {
        // TODO: make configurable / use repository ?
        // TODO: set expire TTL based on 'ts' field (ie. 7 days)
        mongo.getDatabase("jobs-demo").getCollection("job_history")
                .insertOne(new Document(keys));
    }

}


text:
package spark;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import spark.util.SparkTestUtil;

import static spark.Spark.after;
import static spark.Spark.before;
import static spark.Spark.post;

public class BodyAvailabilityTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(BodyAvailabilityTest.class);

    private static final String BODY_CONTENT = "the body content";

    private static SparkTestUtil testUtil;

    private static String beforeBody = null;
    private static String routeBody = null;
    private static String afterBody = null;

    @AfterClass
    public static void tearDown() {
        Spark.stop();

        beforeBody = null;
        routeBody = null;
        afterBody = null;
    }

    @BeforeClass
    public static void setup() {
        LOGGER.debug("setup()");

        testUtil = new SparkTestUtil(4567);

        beforeBody = null;
        routeBody = null;
        afterBody = null;

        before("/hello", (req, res) -> {
            LOGGER.debug("before-req.body() = " + req.body());
            beforeBody = req.body();
        });

        post("/hello", (req, res) -> {
            LOGGER.debug("get-req.body() = " + req.body());
            routeBody = req.body();
            return req.body();
        });

        after("/hello", (req, res) -> {
            LOGGER.debug("after-before-req.body() = " + req.body());
            afterBody = req.body();
        });

        try {
            Thread.sleep(500);
        } catch (Exception e) {
        }
    }

    @Test
    public void testPost() throws Exception {
        SparkTestUtil.UrlResponse response = testUtil.doMethod("POST", "/hello", BODY_CONTENT);
        LOGGER.info(response.body);
        Assert.assertEquals(200, response.status);
        Assert.assertTrue(response.body.contains(BODY_CONTENT));

        Assert.assertEquals(BODY_CONTENT, beforeBody);
        Assert.assertEquals(BODY_CONTENT, routeBody);
        Assert.assertEquals(BODY_CONTENT, afterBody);
    }
}


text:
/**
 * @module
 * @description
 * Entry point for all public APIs of the platform-server package.
 */

import {Version} from '@angular/core';

/**
 * @publicApi
 */
export const VERSION = new Version('0.0.0-PLACEHOLDER');


text:
#pragma once

#ifndef GEODE_SECURITY_CREDENTIALGENERATOR_H_
#define GEODE_SECURITY_CREDENTIALGENERATOR_H_

/**
 * @file    CredentialGenerator.hpp
 * @since   1.0
 * @version 1.0
 * @see
 *
 */

// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------

#include <geode/Properties.hpp>

#ifndef __COMPILE_DUNIT_
#include "fwklib/FwkLog.hpp"
#else
#ifndef FWKINFO
#define FWKINFO(x)
#endif
#ifndef FWKDEBUG
#define FWKDEBUG(x)
#endif
#endif

#include "typedefs.hpp"

#include <ace/OS.h>

#include <map>

namespace apache {
namespace geode {
namespace client {
namespace testframework {
namespace security {

class CredentialGenerator;

/**
 * @class CredentialGenerator CredentialGenerator.hpp
 * Encapsulates valid or invalid credentials required for Client connection
 * and server command parameters to be supplied.
 *

 * Different implementations are there for different kinds of authentication/
 * authorization schemes.
 *

 * Usage:
 *   auto cg = CredentialGenerator::create( schemeStr );
 *   @param schemeStr can be one of the following
 *    DUMMY - simple username/password authentication
 *    LDAP  - LDAP server based authentication.
 *    PKCS  - Digital signature based authentication
 *    NONE  - Disable security altogether.
 *
 * for client connection credentials
 *   cg->getAuthInit(prop);
 *   cg->getValidCredentials(prop);
 *
 * for server command line security arguments
 *   str = cg->getServerCmdParams(":authenticator:authorizer");
 *
 */
class CredentialGenerator {
 public:
  typedef std::map<std::string, std::shared_ptr<CredentialGenerator>> registeredClassMap;

 private:
  ID m_id;
  std::string m_name;
  static registeredClassMap* generatormap;

  CredentialGenerator() : m_id(ID_NONE), m_name("NONE"){};

 protected:
  CredentialGenerator(ID id, std::string name) : m_id(id), m_name(name){};
  CredentialGenerator(const CredentialGenerator& other)
      : m_id(other.m_id), m_name(other.m_name) {}

 public:
  CredentialGenerator& operator=(const CredentialGenerator& other) {
    if (this == &other) return *this;

    this->m_id = other.m_id;
    this->m_name = other.m_name;

    return *this;
  }
  virtual ~CredentialGenerator() {}
  bool operator==(const CredentialGenerator* other) {
    if (other == NULL) return false;
    return (m_id == other->m_id && m_name == other->m_name);
  };

 public:
  static std::shared_ptr<CredentialGenerator> create(std::string scheme);
  static bool registerScheme(std::shared_ptr<CredentialGenerator> scheme) {
    // if not already registered...
    if (generators().find(scheme->m_name) == generators().end()) {
      generators()[scheme->m_name] = scheme;
      return true;
    }
    return false;
  }
  static registeredClassMap& getRegisteredSchemes() { return generators(); }

  static registeredClassMap& generators() {
    if (CredentialGenerator::generatormap == NULL) {
      CredentialGenerator::generatormap = new registeredClassMap;
    }
    return *CredentialGenerator::generatormap;
  }

  ID id() { return m_id; }
  std::string name() { return m_name; }

  std::string toString() {
    char chID[5];
    sprintf(chID, "%d", m_id);
    return std::string(chID) + m_name;
  }
  static void dump() {
    FWKINFO("dumping all registered classes ");
    registeredClassMap::iterator it = generators().begin();
    while (it != generators().end()) {
      FWKINFO(((*it).second)->toString());
      it++;
    }
  }

  void hashCode(){};

  void getAuthInit(std::shared_ptr<Properties>& prop) {
    std::string authinit = this->getClientAuthInitLoaderFactory();
    if (!authinit.empty()) {
      FWKINFO("Authentication initializer : "
              << authinit << " library "
              << this->getClientAuthInitLoaderLibrary());
      prop->insert("security-client-auth-factory", authinit.c_str());
      prop->insert("security-client-auth-library",
                   this->getClientAuthInitLoaderLibrary().c_str());
    }
  }

  std::string getPublickeyfile() {
    char* tempPath = NULL;
    tempPath = ACE_OS::getenv("TESTSRC");
    std::string path = "";
    if (tempPath == NULL) {
      tempPath = ACE_OS::getenv("BUILDDIR");
      path = std::string(tempPath) + "/framework/data";
    } else {
      path = std::string(tempPath);
    }
    char pubfile[1000] = {'\0'};
    sprintf(pubfile, "%s/keystore/publickeyfile", path.c_str());
    return std::string(pubfile);
  }

  std::string getServerCmdParams(std::string securityParams,
                                 std::string workingDir = "",
                                 bool userMode = false) {
    std::string securityCmdStr;
    FWKINFO("User mode is " << userMode);
    if (securityParams.find("authenticator") != std::string::npos &&
        !this->getClientAuthenticator().empty()) {
      securityCmdStr = this->getInitArgs(workingDir, userMode);
      securityCmdStr +=
          std::string(" --J=-Dgemfire.security-client-authenticator=") +
          this->getClientAuthenticator();
    }
    if ((securityParams.find("authorizer") != std::string::npos) &&
        (!this->getClientAuthorizer().empty())) {
      securityCmdStr +=
          std::string(" --J=-Dgemfire.security-client-accessor=") +
          this->getClientAuthorizer();
    }
    if ((securityParams.find("authorizerPP") != std::string::npos) &&
        (!this->getClientAuthorizer().empty())) {
      securityCmdStr +=
          std::string(" --J=-Dgemfire.security-client-accessor-pp=") +
          this->getClientAuthorizer();
    }
    if (m_id == ID_PKI) {
      securityCmdStr +=
          std::string(" --J=-Dgemfire.security-publickey-filepath=") +
          this->getPublickeyfile();
      securityCmdStr +=
          std::string(" --J=-Dgemfire.security-publickey-pass=geode");
    }
    if ((securityParams.find("dummy") != std::string::npos) &&
        (!this->getClientDummyAuthorizer().empty())) {
      securityCmdStr +=
          std::string(" --J=-Dgemfire.security-client-accessor=") +
          this->getClientDummyAuthorizer();
    }
#ifdef __COMPILE_DUNIT_  // lets suppress -N option in case of unit tests.
    int idx;
    while ((idx = securityCmdStr.find("--J=-Dgemfire.", 0)) >= 0) {
      securityCmdStr.replace(idx, 2, "");
    }
#endif
    return securityCmdStr;
  }

  virtual void getValidCredentials(std::shared_ptr<Properties>& p);

  virtual void getInvalidCredentials(std::shared_ptr<Properties>& p);

  virtual void getAllowedCredentialsForOps(opCodeList& opCodes,
                                           std::shared_ptr<Properties>& p,
                                           stringList* regionNames = NULL);

  virtual void getDisallowedCredentialsForOps(opCodeList& opCodes,
                                              std::shared_ptr<Properties>& p,
                                              stringList* regionNames = NULL);

  static registeredClassMap& getRegisterdSchemes() {
    if (generators().size() == 0) {
      // calling for registering the existing schemes.
      create("");
    }
    return generators();
  }

 public:
  virtual std::string getClientAuthInitLoaderFactory() { return ""; }
  virtual std::string getClientAuthInitLoaderLibrary() { return ""; }
  virtual std::string getInitArgs(std::string workingDir, bool userMode);
  virtual std::string getClientAuthenticator() { return ""; }
  virtual std::string getClientAuthorizer() { return ""; }
  virtual std::string getClientDummyAuthorizer() { return ""; }
};

}  // namespace security
}  // namespace testframework
}  // namespace client
}  // namespace geode
}  // namespace apache

#endif  // GEODE_SECURITY_CREDENTIALGENERATOR_H_


text:
package openstack

import (
	"github.com/gophercloud/gophercloud/openstack/networking/v2/networks"
	"github.com/gophercloud/gophercloud/openstack/networking/v2/ports"
	"k8s.io/kops/pkg/resources"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/upup/pkg/fi/cloudup/openstack"
)

const (
	typePort = "Port"
)

func (os *clusterDiscoveryOS) ListPorts(network networks.Network) ([]*resources.Resource, error) {
	var resourceTrackers []*resources.Resource

	ports, err := os.osCloud.ListPorts(ports.ListOpts{
		TenantID:  network.ProjectID,
		NetworkID: network.ID,
	})
	if err != nil {
		return nil, err
	}

	for _, port := range ports {
		resourceTracker := &resources.Resource{
			Name: port.Name,
			ID:   port.ID,
			Type: typePort,
			Deleter: func(cloud fi.Cloud, r *resources.Resource) error {
				return cloud.(openstack.OpenstackCloud).DeletePort(r.ID)
			},
		}
		resourceTrackers = append(resourceTrackers, resourceTracker)
	}
	return resourceTrackers, nil
}


text:
[![License](https://img.shields.io/badge/license-Apache%202-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Localify-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/1791)

### Description

Localify is a small library which allows to load a content from files which are stored under assets and/or raw directory. It can be useful when you have to load some init data or during tests to load mock data.

#### Welcome to fork and pull request.

##### 1.Integration

###### Using Gradle:

```groovy
dependencies {
    compile 'com.github.polok.localify:localify:1.0.0'
}
```

###### Using Maven:

```xml
<dependency>
    <groupId>com.github.polok.localify</groupId>
    <artifactId>localify</artifactId>
    <version>1.0.0</version>
</dependency>
```

##### 2.Usage

###### First you have to init a LocalifyClient (the basic  version) where you have to set the AssetManager and/or the Resources
```java
LocalifyClient localifyClient = new LocalifyClient.Builder()
                .withAssetManager(getAssets()) //If you want to read from raw directory
                .withResources(getResources()) //If you want to read from assets directory
                .build();
```

###### Read a file from assets or raw directory. You can do this in three different ways:
###### 1)
```java
String loadAssetsFile(String fileName);
String loadRawFile(@RawRes int fileNameRawId);
```

```java
//Read from assets directory
String dataAssets = localifyClient.localify().loadAssetsFile("test.text");

//Read from raw directory
String dataRaw = localifyClient.localify().loadRawFile(R.raw.test);
```

###### 2)
```java
void loadAssetsFile(String fileName, LocalifyCallback<T> callback);
void loadRawFile(@RawRes int fileNameRawId, LocalifyCallback<T> callback);
```

```java
//Read from assets directory
localifyClient.localify()
            .async()
            .loadAssetsFile("test.txt", new LocalifyCallback<String>() {
                @Override
                public void onSuccess(String data) {
                }

                @Override
                public void onError(Throwable throwable) {
                }
            });

//Read from raw directory
localifyClient.localify()
            .async()
            .loadRawFile(R.raw.test, new LocalifyCallback<String>() {
                @Override
                public void onSuccess(String data) {
                }

                @Override
                public void onError(Throwable throwable) {
                }
            });
```

###### 3)
```java
Observable<String> loadAssetsFile(String fileName);
Observable<String> loadRawFile(@RawRes int fileNameRawId);
```

```java
localifyClient.localify()
            .rx()
            .loadAssetsFile("test.txt")
            .subscribeOn(Schedulers.io())
            .subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onNext(String s) {
                }
            });

localifyClient.localify()
            .rx()
            .loadRawFile(R.raw.test)
            .subscribeOn(Schedulers.io())
            .subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onNext(String s) {
                }
            });

```

#### 3. Additional settings

By default asynchronous callbacks run in Android main thread. If you want this can be changed by 'withExecutor(executor)' method invoked on LocalifyCalient's builder:

```java
LocalifyClient localifyClient = new LocalifyClient.Builder()
            .withExecutor(....)
            ...
            .build();

```

#### 4. More examples
###### Load json file and map to object
```java
localifyClient.localify()
            .rx()
            .loadAssetsFile("test.json")
            .subscribeOn(Schedulers.io())
            .map(new Func1<String, User>() {
                @Override
                public User call(String data) {
                    Gson gson = new GsonBuilder().create();
                    return gson.fromJson(data, User.class);
                }
            }).subscribe(new Subscriber<User>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onNext(User user) {
                }
        });
```

#### If you want to see more details, go ahead and check the demo!

License
--------

    Copyright 2015 Marcin Polak

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
from sqlalchemy import ARRAY, BigInteger, and_, cast
from sqlalchemy.dialects.postgresql import array

from osm_validator.models import Issue, OSMLine, OSMPoint, OSMPolygon
from osm_validator.validators.base import BaseValidator

class TagsValidator(BaseValidator):

    handle = None

    def __init__(self, conn):
        super().__init__()
        self.conn = conn

    def check_tags_in_db(self, table):
        raise NotImplementedError()

    def check_tags_in_change(self, element):
        raise NotImplementedError()

    async def init(self):
        points = await (await self.conn.execute(OSMPoint.__table__.select().where(
            self.check_tags_in_db(OSMPoint)
        ))).fetchall()
        lines = await (await self.conn.execute(OSMLine.__table__.select().where(
            self.check_tags_in_db(OSMLine)
        ))).fetchall()
        polygons = await (await self.conn.execute(OSMPolygon.__table__.select().where(
            self.check_tags_in_db(OSMPolygon)
        ))).fetchall()

        return [
            Issue(
                handle=self.handle,
                affected_node_ids=[point.osm_id],
            ) for point in points
        ] + [
            Issue(
                handle=self.handle,
                affected_way_ids=[line.osm_id],
            ) for line in lines
        ] + [
            Issue(
                handle=self.handle,
                affected_way_ids=[polygon.osm_id],
            ) for polygon in polygons if polygon.osm_id > 0
        ] + [
            Issue(
                handle=self.handle,
                affected_rel_ids=[-polygon.osm_id],
            ) for polygon in polygons if polygon.osm_id < 0
        ]

    async def _get_osm_objects_with_issues(self, changes):
        node_issues_set = {Issue(**i) for i in (await (await self.conn.execute(
            Issue.__table__.select().where(and_(
                Issue.__table__.c.handle == self.handle,
                Issue.__table__.c.date_closed is not None,
                Issue.__table__.c.affected_node_ids.overlap(
                    cast(array(changes.affected_node_ids), ARRAY(BigInteger))),
            ))
        )).fetchall())}
        way_issues_set = {Issue(**i) for i in (await (await self.conn.execute(
            Issue.__table__.select().where(and_(
                Issue.__table__.c.handle == self.handle,
                Issue.__table__.c.date_closed is not None,
                Issue.__table__.c.affected_way_ids.overlap(
                    cast(array(changes.affected_way_ids), ARRAY(BigInteger))),
            ))
        )).fetchall())}
        rel_issues_set = {Issue(**i) for i in (await (await self.conn.execute(
            Issue.__table__.select().where(and_(
                Issue.__table__.c.handle == self.handle,
                Issue.__table__.c.date_closed is not None,
                Issue.__table__.c.affected_rel_ids.overlap(
                    cast(array(changes.affected_rel_ids), ARRAY(BigInteger))),
            ))
        )).fetchall())}
        node_issues = {n: i for i in node_issues_set for n in i.affected_node_ids}
        way_issues = {w: i for i in way_issues_set for w in i.affected_way_ids}
        rel_issues = {r: i for i in rel_issues_set for r in i.affected_rel_ids}

        return node_issues, way_issues, rel_issues

    def _new_issues_for_created_objects(self, changed_objects, affected_type):
        for element in changed_objects:
            if self.check_tags_in_change(element):
                issue = Issue(
                    handle=self.handle,
                    changeset_created_id=element.changeset,
                    user_created_id=element.uid,
                    date_created=element.timestamp,
                    **{affected_type: [element.id]},
                )
                yield issue

    def _new_issues_for_updated_objects(self, changed_objects, object_issue_map, affected_type):
        for element in changed_objects:
            if self.check_tags_in_change(element) and element.id not in object_issue_map:
                issue = Issue(
                    handle=self.handle,
                    changeset_created_id=element.changeset,
                    user_created_id=element.uid,
                    date_created=element.timestamp,
                    **{affected_type: [element.id]},
                )
                yield issue

    def _closed_issues_for_updated_objects(self, changed_objects, object_issue_map):
        for element in changed_objects:
            if not self.check_tags_in_change(element) and element.id in object_issue_map:
                issue = object_issue_map[element.id]
                issue.changeset_closed_id = element.changeset
                issue.user_closed_id = element.uid
                issue.date_closed = element.timestamp
                yield issue

    def _closed_issues_for_deleted_objects(self, changed_objects, object_issue_map):
        for element in changed_objects:
            if element.id in object_issue_map:
                issue = object_issue_map[element.id]
                issue.changeset_closed_id = element.changeset
                issue.user_closed_id = element.uid
                issue.date_closed = element.timestamp
                yield issue

    async def check(self, changes):
        new = []
        closed = []

        node_issues, way_issues, rel_issues = await self._get_osm_objects_with_issues(changes)

        for change in changes.changes:
            new.extend(self._new_issues_for_created_objects(
                change.created_nodes, 'affected_node_ids'))
            new.extend(self._new_issues_for_created_objects(
                change.created_ways, 'affected_way_ids'))
            new.extend(self._new_issues_for_created_objects(
                change.created_relations, 'affected_rel_ids'))

            new.extend(self._new_issues_for_updated_objects(
                change.modified_nodes, node_issues, 'affected_node_ids'))
            new.extend(self._new_issues_for_updated_objects(
                change.modified_ways, way_issues, 'affected_way_ids'))
            new.extend(self._new_issues_for_updated_objects(
                change.modified_relations, rel_issues, 'affected_rel_ids'))

            closed.extend(self._closed_issues_for_updated_objects(
                change.modified_nodes, node_issues))
            closed.extend(self._closed_issues_for_updated_objects(
                change.modified_ways, way_issues))
            closed.extend(self._closed_issues_for_updated_objects(
                change.modified_relations, rel_issues))

            closed.extend(self._closed_issues_for_deleted_objects(
                change.deleted_nodes, node_issues))
            closed.extend(self._closed_issues_for_deleted_objects(
                change.deleted_ways, way_issues))
            closed.extend(self._closed_issues_for_deleted_objects(
                change.deleted_relations, rel_issues))

        return new, closed


text:
{-# LANGUAGE CPP #-}
-- | DFOV (Digital Field of View) implemented according to specification at <http://roguebasin.roguelikedevelopment.org/index.php?title=Digital_field_of_view_implementation>.
-- This fast version of the algorithm, based on "PFOV", has AFAIK
-- never been described nor implemented before.
module Game.LambdaHack.Server.Fov.Digital
  ( scan
#ifdef EXPOSE_INTERNAL
    -- * Internal operations
  , dline, dsteeper, intersect, _debugSteeper, _debugLine
#endif
  ) where

import Control.Exception.Assert.Sugar

import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Server.Fov.Common

-- | Calculates the list of tiles, in @Bump@ coordinates, visible from (0, 0),
-- within the given sight range.
scan :: Distance        -- ^ visiblity distance
     -> (Bump -> Bool)  -- ^ clear tile predicate
     -> [Bump]
{-# INLINE scan #-}
scan r isClear = assert (r > 0 `blame` r) $
  -- The scanned area is a square, which is a sphere in the chessboard metric.
  dscan 1 ( (Line (B 1 0) (B (-r) r), [B 0 0])
          , (Line (B 0 0) (B (r+1) r), [B 1 0]) )
 where
  dscan :: Distance -> EdgeInterval -> [Bump]
  dscan d ( s0@(sl{-shallow line-}, sHull0)
          , e@(el{-steep line-}, eHull) ) =

    let !ps0 = let (n, k) = intersect sl d  -- minimal progress to consider
               in n `div` k
        !pe = let (n, k) = intersect el d   -- maximal progress to consider
                -- Corners obstruct view, so the steep line, constructed
                -- from corners, is itself not a part of the view,
                -- so if its intersection with the line of diagonals is only
                -- at a corner, choose the diamond leading to a smaller view.
              in -1 + n `divUp` k
        inside = [B p d | p <- [ps0..pe]]
        outside
          | d >= r = []
          | isClear (B ps0 d) = mscanVisible s0 (ps0+1)  -- start visible
          | otherwise = mscanShadowed (ps0+1)            -- start in shadow

        -- We're in a visible interval.
        mscanVisible :: Edge -> Progress -> [Bump]
        {-# INLINE mscanVisible #-}
        mscanVisible s = go
         where
          go ps | ps > pe = dscan (d+1) (s, e)       -- reached end, scan next
                | not $ isClear steepBump =          -- entering shadow
                    mscanShadowed (ps+1)
                    ++ dscan (d+1) (s, (dline nep steepBump, neHull))
                | otherwise = go (ps+1)  -- continue in visible area
           where
            steepBump = B ps d
            gte :: Bump -> Bump -> Bool
            {-# INLINE gte #-}
            gte = dsteeper steepBump
            nep = maximal gte (snd s)
            neHull = addHull gte steepBump eHull

        -- We're in a shadowed interval.
        mscanShadowed :: Progress -> [Bump]
        mscanShadowed ps
          | ps > pe = []                       -- reached end while in shadow
          | isClear shallowBump =              -- moving out of shadow
              mscanVisible (dline nsp shallowBump, nsHull) (ps+1)
          | otherwise = mscanShadowed (ps+1)   -- continue in shadow
         where
          shallowBump = B ps d
          gte :: Bump -> Bump -> Bool
          {-# INLINE gte #-}
          gte = flip $ dsteeper shallowBump
          nsp = maximal gte eHull
          nsHull = addHull gte shallowBump sHull0

    in assert (r >= d && d >= 0 && pe >= ps0 `blame` (r,d,s0,e,ps0,pe)) $
       inside ++ outside

-- | Create a line from two points. Debug: check if well-defined.
dline :: Bump -> Bump -> Line
{-# INLINE dline #-}
dline p1 p2 =
  let line = Line p1 p2
  in
#ifdef WITH_EXPENSIVE_ASSERTIONS
    assert (uncurry blame $ _debugLine line)
#endif
      line

-- | Compare steepness of @(p1, f)@ and @(p2, f)@.
-- Debug: Verify that the results of 2 independent checks are equal.
dsteeper :: Bump -> Bump -> Bump -> Bool
{-# INLINE dsteeper #-}
dsteeper f p1 p2 =
#ifdef WITH_EXPENSIVE_ASSERTIONS
  assert (res == _debugSteeper f p1 p2)
#endif
    res
 where res = steeper f p1 p2

-- | The X coordinate, represented as a fraction, of the intersection of
-- a given line and the line of diagonals of diamonds at distance
-- @d@ from (0, 0).
intersect :: Line -> Distance -> (Int, Int)
{-# INLINE intersect #-}
intersect (Line (B x y) (B xf yf)) d =
#ifdef WITH_EXPENSIVE_ASSERTIONS
  assert (allB (>= 0) [y, yf])
#endif
    ((d - y)*(xf - x) + x*(yf - y), yf - y)
{-
Derivation of the formula:
The intersection point (xt, yt) satisfies the following equalities:
yt = d
(yt - y) (xf - x) = (xt - x) (yf - y)
hence
(yt - y) (xf - x) = (xt - x) (yf - y)
(d - y) (xf - x) = (xt - x) (yf - y)
(d - y) (xf - x) + x (yf - y) = xt (yf - y)
xt = ((d - y) (xf - x) + x (yf - y)) / (yf - y)

General remarks:
A diamond is denoted by its left corner. Hero at (0, 0).
Order of processing in the first quadrant rotated by 45 degrees is
 45678
  123
   @
so the first processed diamond is at (-1, 1). The order is similar
as for the restrictive shadow casting algorithm and reversed wrt PFOV.
The line in the curent state of mscan is called the shallow line,
but it's the one that delimits the view from the left, while the steep
line is on the right, opposite to PFOV. We start scanning from the left.

The Point coordinates are cartesian. The Bump coordinates are cartesian,
translated so that the hero is at (0, 0) and rotated so that he always
looks at the first (rotated 45 degrees) quadrant. The (Progress, Distance)
cordinates coincide with the Bump coordinates, unlike in PFOV.
-}

-- | Debug functions for DFOV:

-- | Debug: calculate steeper for DFOV in another way and compare results.
_debugSteeper :: Bump -> Bump -> Bump -> Bool
{-# INLINE _debugSteeper #-}
_debugSteeper f@(B _xf yf) p1@(B _x1 y1) p2@(B _x2 y2) =
  assert (allB (>= 0) [yf, y1, y2]) $
  let (n1, k1) = intersect (Line p1 f) 0
      (n2, k2) = intersect (Line p2 f) 0
  in n1 * k2 >= k1 * n2

-- | Debug: check if a view border line for DFOV is legal.
_debugLine :: Line -> (Bool, String)
{-# INLINE _debugLine #-}
_debugLine line@(Line (B x1 y1) (B x2 y2))
  | not (allB (>= 0) [y1, y2]) =
      (False, "negative coordinates: " ++ show line)
  | y1 == y2 && x1 == x2 =
      (False, "ill-defined line: " ++ show line)
  | y1 == y2 =
      (False, "horizontal line: " ++ show line)
  | crossL0 =
      (False, "crosses the X axis below 0: " ++ show line)
  | crossG1 =
      (False, "crosses the X axis above 1: " ++ show line)
  | otherwise = (True, "")
 where
  (n, k)  = line `intersect` 0
  (q, r)  = if k == 0 then (0, 0) else n `divMod` k
  crossL0 = q < 0  -- q truncated toward negative infinity
  crossG1 = q >= 1 && (q > 1 || r /= 0)


text:
package com.wincom.mstar.domain;

public class CDeviceTypeEx {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column nfjd502.dbo.CDeviceTypeEx.DeviceID
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    private Integer deviceid;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column nfjd502.dbo.CDeviceTypeEx.DeviceName
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    private String devicename;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column nfjd502.dbo.CDeviceTypeEx.DeviceTypeProperty
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    private Integer devicetypeproperty;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column nfjd502.dbo.CDeviceTypeEx.DeviceID
     *
     * @return the value of nfjd502.dbo.CDeviceTypeEx.DeviceID
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public Integer getDeviceid() {
        return deviceid;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column nfjd502.dbo.CDeviceTypeEx.DeviceID
     *
     * @param deviceid the value for nfjd502.dbo.CDeviceTypeEx.DeviceID
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public void setDeviceid(Integer deviceid) {
        this.deviceid = deviceid;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column nfjd502.dbo.CDeviceTypeEx.DeviceName
     *
     * @return the value of nfjd502.dbo.CDeviceTypeEx.DeviceName
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public String getDevicename() {
        return devicename;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column nfjd502.dbo.CDeviceTypeEx.DeviceName
     *
     * @param devicename the value for nfjd502.dbo.CDeviceTypeEx.DeviceName
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public void setDevicename(String devicename) {
        this.devicename = devicename == null ? null : devicename.trim();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column nfjd502.dbo.CDeviceTypeEx.DeviceTypeProperty
     *
     * @return the value of nfjd502.dbo.CDeviceTypeEx.DeviceTypeProperty
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public Integer getDevicetypeproperty() {
        return devicetypeproperty;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column nfjd502.dbo.CDeviceTypeEx.DeviceTypeProperty
     *
     * @param devicetypeproperty the value for nfjd502.dbo.CDeviceTypeEx.DeviceTypeProperty
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public void setDevicetypeproperty(Integer devicetypeproperty) {
        this.devicetypeproperty = devicetypeproperty;
    }
}


text:
using System;

namespace Weingartner.Json.Migration.Common
{
    public class MigrationException : Exception
    {
        public MigrationException()
        {
        }

        public MigrationException(string message) : base(message)
        {
        }

        public MigrationException(string message, Exception inner) : base(message, inner)
        {
        }
    }
}


text:
export default function() {

}

export var x = 99;


text:
[See html formatted version](https://huasofoundries.github.io/google-maps-documentation/AutocompletionRequest.html)

AutocompletionRequest interface
-------------------------------

google.maps.places.AutocompletionRequest interface

An Autocompletion request to be sent to [AutocompleteService.getPlacePredictions](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompleteService.getPlacePredictions).

#### Library

places

Properties

[bounds](#AutocompletionRequest.bounds)

**Type:**  [LatLngBounds](LatLngBounds.md)|[LatLngBoundsLiteral](LatLngBoundsLiteral.md)

Bounds for prediction biasing. Predictions will be biased towards, but not restricted to, the given bounds. Both location and radius will be ignored if bounds is set.

[componentRestrictions](#AutocompletionRequest.componentRestrictions)

**Type:**  [ComponentRestrictions](ComponentRestrictions.md)

The component restrictions. Component restrictions are used to restrict predictions to only those within the parent component. For example, the country.

[input](#AutocompletionRequest.input)

**Type:**  string

The user entered input string.

[location](#AutocompletionRequest.location)

**Type:**  [LatLng](LatLng.md)

Location for prediction biasing. Predictions will be biased towards the given location and radius. Alternatively, bounds can be used.

[offset](#AutocompletionRequest.offset)

**Type:**  number

The character position in the input term at which the service uses text for predictions (the position of the cursor in the input field).

[radius](#AutocompletionRequest.radius)

**Type:**  number

The radius of the area used for prediction biasing. The radius is specified in meters, and must always be accompanied by a location property. Alternatively, bounds can be used.

[sessionToken](#AutocompletionRequest.sessionToken)

**Type:**  [AutocompleteSessionToken](AutocompleteSessionToken.md)

Unique reference used to bundle individual requests into sessions.

[types](#AutocompletionRequest.types)

**Type:**  Array<string>

The types of predictions to be returned. For a list of supported types, see the [developer's guide](https://developers.google.com/places/supported_types#table3). If nothing is specified, all types are returned. In general only a single type is allowed. The exception is that you can safely mix the 'geocode' and 'establishment' types, but note that this will have the same effect as specifying no types.


text:
@class ReaderThumbRequest;

@interface ReaderThumbFetch : ReaderThumbOperation
{
@private
	ReaderThumbRequest *request;
}

- (id)initWithRequest:(ReaderThumbRequest *)object;

@end


text:
package com.hazelcast.spi.impl;

import com.hazelcast.test.ExpectedRuntimeException;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class AbstractInvocationFuture_MiscTest extends AbstractInvocationFuture_AbstractTest {

    @Test
    public void toString_whenNotCompleted() {
        String s = future.toString();
        assertEquals("InvocationFuture{invocation=someinvocation, done=false}", s);
    }

    @Test
    public void toString_whenCompleted() {
        future.complete(value);
        String s = future.toString();
        assertEquals("InvocationFuture{invocation=someinvocation, value=somevalue}", s);
    }

    @Test
    public void getNumberOfDependents_whenNoneRegistered() {
        assertEquals(0, future.getNumberOfDependents());
    }

    @Test
    public void getNumberOfDependents_whenSomeRegistered() {
        future.whenCompleteAsync((v, t) -> ignore(null));
        future.thenRun(() -> ignore(null));
        assertEquals(2, future.getNumberOfDependents());
    }

    @Test
    public void getNumberOfDependents_whenOneIsRegistered() {
        future.thenRun(() -> ignore(null));
        assertEquals(1, future.getNumberOfDependents());
    }

    @Test
    public void obtrudeValue_whenIncomplete() {
        future.obtrudeValue(value);

        assertSame(value, future.join());
    }

    @Test
    public void obtrudeValue_whenComplete() {
        future.complete("this will be overwritten");
        future.obtrudeValue(value);

        assertSame(value, future.join());
    }

    @Test
    public void obtrudeValue_triggersUntriggeredStages() {
        InternalCompletableFuture nextStage = future.thenAccept(v -> assertSame(value, v));
        future.obtrudeValue(value);

        assertSame(value, future.join());
        // ensure the consumer was executed and no exception was thrown
        nextStage.join();
    }

    @Test
    public void obtrudeException_whenNotComplete() {
        future.obtrudeException(new ExpectedRuntimeException());

        try {
            future.joinInternal();
            fail();
        } catch (ExpectedRuntimeException e) {
            ignore(e);
        }
    }

    @Test
    public void obtrudeException_whenComplete() {
        future.complete(value);
        future.obtrudeException(new ExpectedRuntimeException());

        try {
            future.joinInternal();
            fail();
        } catch (ExpectedRuntimeException e) {
            ignore(e);
        }
    }
}


text:
import numpy as np
from datetime import datetime
import netCDF4 as netCDF

import pyroms
import pyroms_toolbox

##  load 2-dimentional interannual discharge data
##  from 1948-2007. See Dai and Trenberth (2002) and Dai et al. (2009)
print 'Load interannual discharge data'
nc_data = netCDF.Dataset('/archive/u1/uaf/kate/CORE2/runoff.daitren.iaf.10FEB2011.nc', 'r')
runoff = nc_data.variables['runoff'][:]
lon = nc_data.variables['xc'][:]
lat = nc_data.variables['yc'][:]
lon_corner = nc_data.variables['xv'][:]
lat_corner = nc_data.variables['yv'][:]
mask = nc_data.variables['mask'][:]

##  create data remap file for scrip
print 'Create remap grid file for Dai and Trenberth runoff'
remap_filename = 'remap_grid_daitren.nc'
nc = netCDF.Dataset(remap_filename, 'w', format='NETCDF3_CLASSIC')
nc.Description = 'remap grid file for Dai and Trenberth runoff data'
nc.Author = 'build_runoff'
nc.Created = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
nc.title = 'Dai and Trenberth runoff'

grid_center_lon = lon.flatten()
grid_center_lat = lat.flatten()
Mp, Lp = lon.shape
grid_imask = mask.flatten()
grid_size = Lp * Mp
grid_corner_lon = np.zeros((grid_size, 4))
grid_corner_lat = np.zeros((grid_size, 4))
k = 0
for j in range(Mp):
    for i in range(Lp):
        grid_corner_lon[k,0] = lon_corner[0,j,i]
        grid_corner_lat[k,0] = lat_corner[0,j,i]
        grid_corner_lon[k,1] = lon_corner[1,j,i]
        grid_corner_lat[k,1] = lat_corner[1,j,i]
        grid_corner_lon[k,2] = lon_corner[2,j,i]
        grid_corner_lat[k,2] = lat_corner[2,j,i]
        grid_corner_lon[k,3] = lon_corner[3,j,i]
        grid_corner_lat[k,3] = lat_corner[3,j,i]
        k = k + 1

nc.createDimension('grid_size', grid_size)
nc.createDimension('grid_corners', 4)
nc.createDimension('grid_rank', 2)

nc.createVariable('grid_dims', 'i4', ('grid_rank'))
nc.variables['grid_dims'].long_name = 'grid size along x and y axis'
nc.variables['grid_dims'].units = 'None'
nc.variables['grid_dims'][:] = [(Lp, Mp)]

nc.createVariable('grid_center_lon', 'f8', ('grid_size'))
nc.variables['grid_center_lon'].long_name = 'longitude of cell center'
nc.variables['grid_center_lon'].units = 'degrees'
nc.variables['grid_center_lon'][:] = grid_center_lon

nc.createVariable('grid_center_lat', 'f8', ('grid_size'))
nc.variables['grid_center_lat'].long_name = 'latitude of cell center'
nc.variables['grid_center_lat'].units = 'degrees'
nc.variables['grid_center_lat'][:] = grid_center_lat

nc.createVariable('grid_imask', 'i4', ('grid_size'))
nc.variables['grid_imask'].long_name = 'mask'
nc.variables['grid_imask'].units = 'None'
nc.variables['grid_imask'][:] = grid_imask

nc.createVariable('grid_corner_lon', 'f8', ('grid_size', 'grid_corners'))
nc.variables['grid_corner_lon'].long_name = 'longitude of cell corner'
nc.variables['grid_corner_lon'].units = 'degrees'
nc.variables['grid_corner_lon'][:] = grid_corner_lon

nc.createVariable('grid_corner_lat', 'f8', ('grid_size', 'grid_corners'))
nc.variables['grid_corner_lat'].long_name = 'latitude of cell corner'
nc.variables['grid_corner_lat'].units = 'degrees'
nc.variables['grid_corner_lat'][:] = grid_corner_lat

nc.close()

##  create NWGOA remap file for scrip
print 'Create remap grid file for NWGOA grid'
dstgrd = pyroms.grid.get_ROMS_grid('NWGOA')
dstgrd.hgrid.mask_rho = np.ones(dstgrd.hgrid.mask_rho.shape)
pyroms.remapping.make_remap_grid_file(dstgrd, Cpos='rho')

## compute remap weights
print 'compute remap weights using scrip'
# input namelist variables for conservative remapping at rho points
grid1_file = 'remap_grid_daitren.nc'
grid2_file = 'remap_grid_NWGOA_rho.nc'
interp_file1 = 'remap_weights_daitren_to_NWGOA_conservative_nomask.nc'
interp_file2 = 'remap_weights_NWGOA_to_daitren_conservative_nomask.nc'
map1_name = 'daitren to NWGOA conservative Mapping'
map2_name = 'NWGOA to daitren conservative Mapping'
num_maps = 1
map_method = 'conservative'

pyroms.remapping.compute_remap_weights(grid1_file, grid2_file, \
              interp_file1, interp_file2, map1_name, \
              map2_name, num_maps, map_method)


text:
from unittest import TestCase
from mock import Mock, patch
from ming.odm import ThreadLocalORMSession

from allura.tests import TestController
from allura import model as M

# important to be distinct from 'test' which ForgeSVN uses, so that the
# tests can run in parallel and not clobber each other
test_project_with_repo = 'test2'

from forgeimporters.google.code import (
    get_repo_url,
    GoogleRepoImporter,
)

class TestGetRepoUrl(TestCase):

    def test_svn(self):
        r = get_repo_url('projname', 'svn')
        self.assertEqual(r, 'http://projname.googlecode.com/svn/')

    def test_git(self):
        r = get_repo_url('projname', 'git')
        self.assertEqual(r, 'https://code.google.com/p/projname/')

    def test_hg(self):
        r = get_repo_url('projname', 'hg')
        self.assertEqual(r, 'https://code.google.com/p/projname/')

class TestGoogleRepoImporter(TestCase):

    def _make_project(self, gc_proj_name=None):
        project = Mock()
        project.get_tool_data.side_effect = lambda *args: gc_proj_name
        return project

    @patch('forgeimporters.google.code.g')
    @patch('forgeimporters.google.code.M')
    @patch('forgeimporters.google.code.GoogleCodeProjectExtractor')
    @patch('forgeimporters.google.code.get_repo_url')
    def test_import_tool_happy_path(self, get_repo_url, gcpe, M, g):
        gcpe.return_value.get_repo_type.return_value = 'git'
        get_repo_url.return_value = 'http://remote/clone/url/'
        p = self._make_project(gc_proj_name='myproject')
        u = Mock(name='c.user')
        app = p.install_app.return_value
        app.config.options.mount_point = 'code'
        app.url = 'foo'
        GoogleRepoImporter().import_tool(p, u, project_name='project_name')
        get_repo_url.assert_called_once_with('project_name', 'git')
        p.install_app.assert_called_once_with('git',
                                              mount_point='code',
                                              mount_label='Code',
                                              init_from_url='http://remote/clone/url/',
                                              import_id={
                                                  'source': 'Google Code',
                                                  'project_name': 'project_name',
                                              },
                                              )
        M.AuditLog.log.assert_called_once_with(
            'import tool code from project_name on Google Code',
            project=p, user=u, url='foo')
        g.post_event.assert_called_once_with('project_updated')

class TestGoogleRepoImportController(TestController, TestCase):

    def test_index(self):
        r = self.app.get(
            '/p/{}/admin/ext/import/google-code-repo/'.format(test_project_with_repo))
        self.assertIsNotNone(r.html.find(attrs=dict(name="gc_project_name")))
        self.assertIsNotNone(r.html.find(attrs=dict(name="mount_label")))
        self.assertIsNotNone(r.html.find(attrs=dict(name="mount_point")))

    @patch('forgeimporters.google.code.GoogleCodeProjectExtractor')
    @patch('forgeimporters.base.import_tool')
    def test_create(self, import_tool, extractor):
        extractor.return_value.get_repo_type.return_value = 'git'
        params = dict(gc_project_name='poop',
                      mount_label='mylabel',
                      mount_point='mymount',
                      )
        r = self.app.post(
            '/p/{}/admin/ext/import/google-code-repo/create'.format(test_project_with_repo),
            params,
            status=302)
        self.assertEqual(
            r.location, 'http://localhost/p/{}/admin/'.format(test_project_with_repo))
        self.assertEqual(
            u'mymount', import_tool.post.call_args[1]['mount_point'])
        self.assertEqual(
            u'mylabel', import_tool.post.call_args[1]['mount_label'])
        self.assertEqual(
            u'poop', import_tool.post.call_args[1]['project_name'])

    @patch('forgeimporters.google.code.GoogleCodeProjectExtractor')
    @patch('forgeimporters.base.import_tool')
    def test_create_limit(self, import_tool, extractor):
        extractor.return_value.get_repo_type.return_value = 'git'
        project = M.Project.query.get(shortname=test_project_with_repo)
        project.set_tool_data('GoogleRepoImporter', pending=1)
        ThreadLocalORMSession.flush_all()
        params = dict(gc_project_name='poop',
                      mount_label='mylabel',
                      mount_point='mymount',
                      )
        r = self.app.post(
            '/p/{}/admin/ext/import/google-code-repo/create'.format(test_project_with_repo),
            params,
            status=302).follow()
        self.assertIn('Please wait and try again', r)
        self.assertEqual(import_tool.post.call_count, 0)


text:
MiniFrame::MiniFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize &size)
    : wxMiniFrame(parent, id, title, position, size, wxCAPTION | wxCLOSE_BOX | wxFRAME_NO_TASKBAR)
{
    Bind(wxEVT_CLOSE_WINDOW, &MiniFrame::OnClosed, this);
}

void MiniFrame::ToggleVisibility()
{
    Show(!IsShown());
}

void MiniFrame::OnClosed(wxCloseEvent &event)
{
    Show(false);
}


text:
Summary
-------

Icon Composer 2x is a replacement for Apple's Icon Composer that supports Retina Resolution Icons.

Prebuilt binaries are available [here](https://github.com/lemonmojo/IconComposer2x/releases).

Requires Xcode to be installed or more specifically, iconutil to be stored or linked in /usr/bin/iconutil.

License
-------

[New BSD License](http://en.wikipedia.org/wiki/BSD_licenses). For the full license text, see [here](https://raw.github.com/LemonMojo/IconComposer2x/master/License).

Credits
-------
Icon Composer 2x was created by [Felix Deimel](https://github.com/LemonMojo).


text:
package org.openrdf.sail.keyword;

import org.openrdf.model.Literal;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.query.algebra.evaluation.ValueExprEvaluationException;
import org.openrdf.query.algebra.evaluation.function.Function;

/**
 * Generates a regex that will match strings with a given keyword.
 *
 * @author James Leigh
 *
 */
public class Regex implements Function {
	private final String uri = "http://www.openrdf.org/rdf/2011/keyword#regex";
	private final PhoneHelper helper = PhoneHelperFactory.newInstance()
			.createPhoneHelper();

	public String toString() {
		return getURI();
	}

	public String getURI() {
		return uri;
	}

	public Literal evaluate(ValueFactory vf, Value... args)
			throws ValueExprEvaluationException {
		if (args == null || args.length < 1)
			return vf.createLiteral(helper.regex(""));
		String word = args[0].stringValue();
		return vf.createLiteral(helper.regex(word));
	}

}


text:
namespace SysCommand.Parsing
{
    /// <summary>
    /// Represents a piece of the command line.
    /// </summary>
    public class ArgumentRaw
    {
        /// <summary>
        /// Position in command line
        /// </summary>
        public int Index { get; set; }

        /// <summary>
        /// Argument name if exists
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Value without scapes
        /// </summary>
        public string Value { get; set; }

        /// <summary>
        /// Argument format
        /// </summary>
        public ArgumentFormat Format { get; set; }

        /// <summary>
        /// Delimiter format if exists
        /// </summary>
        public string DelimiterArgument { get; set; }

        /// <summary>
        /// Value delimiter if exists
        /// </summary>
        public string DelimiterValueInName { get; set; }

        /// <summary>
        /// Value with scapes
        /// </summary>
        public string ValueRaw { get; set; }

        /// <summary>
        /// Check if the format is short
        /// </summary>
        public bool IsShortName
        {
            get
            {
                switch (this.Format)
                {
                    case ArgumentFormat.ShortNameAndHasValue:
                    case ArgumentFormat.ShortNameAndHasValueInName:
                    case ArgumentFormat.ShortNameAndNoValue:
                        return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Check if the format is long
        /// </summary>
        public bool IsLongName
        {
            get
            {
                switch (this.Format)
                {
                    case ArgumentFormat.LongNameAndHasValue:
                    case ArgumentFormat.LongNameAndHasValueInName:
                    case ArgumentFormat.LongNameAndNoValue:
                        return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Initialize
        /// </summary>
        /// <param name="index">Position in command line</param>
        /// <param name="name">Argument name</param>
        /// <param name="valueRaw">Value with scapes</param>
        /// <param name="value">Value without scapes</param>
        /// <param name="format">Argument format</param>
        /// <param name="delimiterArgument">Delimiter format if exists</param>
        /// <param name="delimiterValueInName">Value delimiter if exists</param>
        public ArgumentRaw(int index, string name, string valueRaw, string value, ArgumentFormat format, string delimiterArgument, string delimiterValueInName)
        {
            this.Index = index;
            this.Name = name;
            this.Value = value;
            this.ValueRaw = valueRaw;
            this.Format = format;
            this.DelimiterArgument = delimiterArgument;
            this.DelimiterValueInName = delimiterValueInName;
        }

        public override string ToString()
        {
            return "[" + this.Name + ", " + this.Value + "]";
        }

    }
}


text:
package jp.osd.doce.internal;

/**
 * 動的クラス処理に関するユーティリティクラスです。
 *
 * @author asuka
 */
public class ClassUtils {
	/**
	 * 実装クラス名を取得します。
	 *
	 * @param interfaceClass 実装クラスに対するインタフェースの型
	 * @param packageName 実装クラスのパッケージ名。長さ 0 の場合は interfaceClass のパッケージ名を使用する。
	 * @param subpackageName 実装クラスのサブパッケージ名
	 * @param suffix 実装クラスのクラス名のサフィックス
	 * @return 実装クラス名
	 */
	public static String getImplClassName(Class<?> interfaceClass,
			String packageName, String subpackageName, String suffix) {
		StringBuilder sb = new StringBuilder();
		if (0 < packageName.length()) {
			sb.append(packageName);
		} else {
			sb.append(interfaceClass.getPackage().getName());
		}
		sb.append('.');
		if (0 < subpackageName.length()) {
			sb.append(subpackageName);
			sb.append('.');
		}
		sb.append(interfaceClass.getSimpleName());
		sb.append(suffix);

		return sb.toString();
	}

	private ClassUtils() {
		// 何もしない
	}
}


text:
package cz.habarta.typescript.generator;

import java.io.*;
import java.nio.charset.*;

public class Output {

    private final Writer writer;
    private final String name;
    private final boolean closeWriter;

    private Output(Writer writer, String name, boolean closeWriter) {
        this.writer = writer;
        this.name = name;
        this.closeWriter = closeWriter;
    }

    public Writer getWriter() {
        return writer;
    }

    public String getName() {
        return name;
    }

    public boolean shouldCloseWriter() {
        return closeWriter;
    }

    public static Output to(File file) {
        try {
            file.getParentFile().mkdirs();
            return new Output(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")), file.toString(), true);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static Output to(OutputStream outputStream) {
        return new Output(new OutputStreamWriter(outputStream, Charset.forName("UTF-8")), null, false);
    }

    public static Output to(Writer writer) {
        return new Output(writer, null, false);
    }

}


text:
import functools

from heleosapi import exceptions as h_exc
from neutron.i18n import _LW
from oslo_log import log as logging

from neutron_lbaas.services.loadbalancer import constants as lcon
from neutron_lbaas.services.loadbalancer.drivers.embrane \
    import constants as econ

LOG = logging.getLogger(__name__)
handlers = {}

def handler(event, ahandler):
    def wrap(f):
        if event not in ahandler.keys():
            ahandler[event] = [f]
        else:
            ahandler[event].append(f)

        @functools.wraps(f)
        def wrapped_f(*args, **kwargs):
            return f(*args, **kwargs)

        return wrapped_f

    return wrap

@handler(econ.Events.CREATE_VIP, handlers)
def _provision_load_balancer(driver, context, vip, flavor,
                             vip_utif_info, vip_ip_allocation_info,
                             pool_utif_info=None,
                             pool_ip_allocation_info=None,
                             pool=None, members=None,
                             monitors=None):
    api = driver._heleos_api
    tenant_id = context.tenant_id
    admin_state = vip["admin_state_up"]
    # Architectural configuration
    api.create_load_balancer(tenant_id=tenant_id,
                             router_id=vip["id"],
                             name=vip["name"],
                             flavor=flavor,
                             up=False)
    api.grow_interface(vip_utif_info, False, tenant_id, vip["id"])
    if pool:
        api.grow_interface(pool_utif_info, False, tenant_id,
                           vip["id"])

    # Logical configuration
    api.allocate_address(vip["id"], True, vip_ip_allocation_info)
    if pool:
        api.allocate_address(vip["id"], True, pool_ip_allocation_info)
    dva = api.configure_load_balancer(vip["id"], admin_state,
                                      vip, pool,
                                      monitors, members)
    return api.extract_dva_state(dva)

@handler(econ.Events.UPDATE_VIP, handlers)
def _update_load_balancer(driver, context, vip,
                          old_pool_id=None, old_port_id=None,
                          removed_ip=None, pool_utif_info=None,
                          pool_ip_allocation_info=None,
                          new_pool=None, members=None,
                          monitors=None):
    api = driver._heleos_api
    tenant_id = context.tenant_id
    admin_state = vip["admin_state_up"]

    if old_pool_id:
        # Architectural Changes
        api.de_allocate_address(vip['id'], False, old_port_id, removed_ip)
        api.shrink_interface(tenant_id, vip["id"], False, old_port_id)
        api.grow_interface(pool_utif_info, False, tenant_id, vip["id"])
        # Configuration Changes
        api.allocate_address(vip["id"], True, pool_ip_allocation_info)
        api.replace_pool(vip["id"], True, vip, old_pool_id,
                         new_pool, monitors, members)

    api.update_vservice(vip["id"], True, vip)
    # Dva update
    dva = api.update_dva(tenant_id, vip["id"], vip["name"],
                         admin_state, description=vip["description"])

    return api.extract_dva_state(dva)

@handler(econ.Events.DELETE_VIP, handlers)
def _delete_load_balancer(driver, context, vip):
    try:
        driver._heleos_api.delete_dva(context.tenant_id, vip['id'])
    except h_exc.DvaNotFound:
        LOG.warning(_LW('The load balancer %s had no physical representation, '
                        'likely already deleted'), vip['id'])
    return econ.DELETED

@handler(econ.Events.UPDATE_POOL, handlers)
def _update_server_pool(driver, context, vip, pool,
                        monitors=None):
    api = driver._heleos_api
    cookie = ((vip.get('session_persistence') or {}).get('type') ==
              lcon.SESSION_PERSISTENCE_HTTP_COOKIE)
    return api.extract_dva_state(api.update_pool(vip['id'],
                                                 vip['admin_state_up'],
                                                 pool, cookie, monitors))

@handler(econ.Events.ADD_OR_UPDATE_MEMBER, handlers)
def _add_or_update_pool_member(driver, context, vip, member, protocol):
    api = driver._heleos_api
    return api.extract_dva_state(api.update_backend_server(
        vip['id'], vip['admin_state_up'], member, protocol))

@handler(econ.Events.REMOVE_MEMBER, handlers)
def _remove_member_from_pool(driver, context, vip, member):
    api = driver._heleos_api
    return api.extract_dva_state(api.remove_pool_member(vip['id'],
                                                        vip['admin_state_up'],
                                                        member))

@handler(econ.Events.DELETE_MEMBER, handlers)
def _delete_member(driver, context, vip, member):
    with context.session.begin(subtransactions=True):
        api = driver._heleos_api
        dva = api.delete_backend_server(vip['id'], vip['admin_state_up'],
                                        member)
        driver._delete_member(context, member)
        return api.extract_dva_state(dva)

@handler(econ.Events.ADD_POOL_HM, handlers)
def _create_pool_hm(driver, context, vip, hm, pool_id):
    api = driver._heleos_api
    return api.extract_dva_state(api.add_pool_monitor(
        vip['id'], vip['admin_state_up'], hm, pool_id))

@handler(econ.Events.UPDATE_POOL_HM, handlers)
def _update_pool_hm(driver, context, vip, hm, pool_id):
    api = driver._heleos_api
    return api.extract_dva_state(api.update_pool_monitor(
        vip['id'], vip['admin_state_up'], hm, pool_id))

@handler(econ.Events.DELETE_POOL_HM, handlers)
def _delete_pool_hm(driver, context, vip, hm, pool_id):
    with context.session.begin(subtransactions=True):
        api = driver._heleos_api
        dva = api.add_pool_monitor(vip['id'], vip['admin_state_up'],
                                   hm, pool_id)
        driver._delete_pool_hm(context, hm, pool_id)
        return api.extract_dva_state(dva)

@handler(econ.Events.POLL_GRAPH, handlers)
def _poll_graph(driver, context, vip):
    api = driver._heleos_api
    return api.extract_dva_state(api.get_dva(vip['id']))


text:
package io.github.izzyleung.zhihudailypurify.task;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.github.izzyleung.zhihudailypurify.bean.DailyNews;
import io.github.izzyleung.zhihudailypurify.support.Constants;
import io.github.izzyleung.zhihudailypurify.support.Logger;
import io.github.izzyleung.zhihudailypurify.support.lib.Http;

public class OriginalGetNewsTask extends BaseGetNewsTask {

    public OriginalGetNewsTask(String date, UpdateUIListener callback) {
        super(date, callback);
    }

    @Override
    protected List<DailyNews> doInBackground(Void... params) {
        List<DailyNews> resultNewsList = new ArrayList<>();

        try {
            JSONObject contents = new JSONObject(Http.get(Constants.Url.ZHIHU_DAILY_BEFORE, date));

            JSONArray newsArray = contents.getJSONArray("stories");
            for (int i = 0; i < newsArray.length(); i++) {
                JSONObject singleNews = newsArray.getJSONObject(i);

                DailyNews dailyNews = new DailyNews();
                String thumbnailUrl = "";
                if (singleNews.has("images")) {
                    thumbnailUrl = (String) singleNews.getJSONArray("images").get(0);
                }
                dailyNews.setThumbnailUrl(thumbnailUrl);
                dailyNews.setDailyTitle(singleNews.getString("title"));
                String newsInfoJson = Http.get(Constants.Url.ZHIHU_DAILY_OFFLINE_NEWS,
                        String.valueOf(singleNews.getInt("id")));
                JSONObject newsDetail = new JSONObject(newsInfoJson);
                if (newsDetail.has("body")) {
                    if (updateDailyNews(Jsoup.parse(newsDetail.getString("body")), dailyNews)) {
                        resultNewsList.add(dailyNews);
                    }
                }
            }
        } catch (JSONException | IOException e) {
            isRefreshSuccess = false;
            Logger.e(e);
        }

        isContentSame = checkIsContentSame(resultNewsList);
        return resultNewsList;
    }

    private boolean updateDailyNews(Document doc, DailyNews dailyNews) {
        Elements viewMoreElements = doc.getElementsByClass("view-more");

        if (viewMoreElements.size() > 1) {
            return processMulti(doc, viewMoreElements, dailyNews);
        } else {
            return viewMoreElements.size() == 1 && processSingle(doc, viewMoreElements, dailyNews);
        }
    }

    private boolean processMulti(Document doc, Elements viewMoreElements, DailyNews dailyNews) {
        dailyNews.setMulti(true);
        Elements questionTitleElements = doc.getElementsByClass("question-title");

        for (int j = 0; j < questionTitleElements.size(); j++) {
            if (j == 0 && questionTitleElements.get(j).text().length() == 0) {
                dailyNews.addQuestionTitle(dailyNews.getDailyTitle());
            }

            if (questionTitleElements.get(j).text().equals("原题描述:")) {
                continue;
            }

            dailyNews.addQuestionTitle(questionTitleElements.get(j).text());
        }

        for (Element viewMoreElement : viewMoreElements) {
            Elements viewQuestionElement = viewMoreElement.select("a");

            // Unless the url is a link to zhihu, do not add it to the result NewsList
            if (viewQuestionElement.text().equals("查看知乎讨论")) {
                dailyNews.addQuestionUrl(viewQuestionElement.attr("href"));
            } else {
                return false;
            }
        }

        return true;
    }

    private boolean processSingle(Document doc, Elements viewMoreElements, DailyNews dailyNews) {
        dailyNews.setMulti(false);

        Elements viewQuestionElement = viewMoreElements.select("a");
        if (viewQuestionElement.text().equals("查看知乎讨论")) {
            dailyNews.setQuestionUrl(viewQuestionElement.attr("href"));
        } else {
            return false;
        }

        // Question title is the same with daily title
        if (doc.getElementsByClass("question-title").text().length() == 0) {
            dailyNews.setQuestionTitle(dailyNews.getDailyTitle());
        } else {
            if (doc.getElementsByClass("question-title").size() == 1) {
                dailyNews.setQuestionTitle(doc.getElementsByClass("question-title").text());
            } else {
                for (Element questionTitle : doc.getElementsByClass("question-title")) {
                    if (!(questionTitle.text().equals("原题描述:") || questionTitle.text().equals("原题描述"))) {
                        dailyNews.setQuestionTitle(questionTitle.text());
                        break;
                    }
                }
            }
        }

        return true;
    }
}


text:
var Query = require('azure-query-js').Query,
    Platform = require('./Platform');

// Copy select Query operators to the table so queries can be created
// compactly.  We'll just add them to the table prototype and then
// forward on directly to a new Query instance.
var queryOperators = ['where', 'select', 'orderBy', 'orderByDescending', 'skip', 'take', 'includeTotalCount'];

var copyOperator = function (table, operator) {
    table.prototype[operator] = function () {
        /// <summary>
        /// Creates a new query.
        /// </summary>

        // Create a query associated with this table
        var table = this;
        var query = new Query(table.getTableName());

        // Add a .read() method on the query which will execute the query.
        // This method is defined here per query instance because it's
        // implicitly tied to the table.
        query.read = function (parameters) {
            return table.read(query, parameters);
        };

        // Invoke the query operator on the newly created query
        return query[operator].apply(query, arguments);
    };
};

function defineQueryOperators(table) {
    var i = 0;
    for (; i < queryOperators.length; i++) {
        copyOperator(table, queryOperators[i]);
    }
}

exports.defineQueryOperators = defineQueryOperators;


text:
<?php

class user {

	// Protected properties of user
	protected $user_id;       // [string]
	protected $user_name;     // [string]     username

	/**
	 * Constructor. Both fields required.
	 */
	function __construct($user_id, $user_name){
		$this->user_id = $user_id;
		$this->user_name = $user_name;
	}

	/**
	 * Function displayAsTableRow
	 *
	 * Outputs current user as a row of a table; primarily used for debugging
	 *
	 * @param  [boolean] $headers Specify whether or not to include a row of headers directly before this user
	 * @return [string] Table row of user properties, as a string
	 */
	public function displayAsTableRow($headers) {
		// Set up headers
		$addHeaders = "
user_id	";
		$addHeaders .= "user_name	";
		$addHeaders .= "
";

		// If request for headers
		$output   = ($headers) ? $addHeaders : "";

		// Add each cell
		$output .= "
" . $this->user_id . "	";
		$output .= "" . $this->user_name . "	";
		$output .= "
";

		//done
		return $output;
	}

	/**
	 * Function addToDB
	 *
	 * Adds user to the database if there is not already an entry at its user_id. NOTE:
	 * This should only be used to add NEW users to the database, never to update
	 * existing users.
	 *
	 * @global [$log | The open log file]
	 * @return void
	 */
	public function addToDB() {
		global $log;

		// Check if there is a user already with this new user's user_id
		$checkQuery = "
		SELECT *
		FROM   users
		WHERE  user_id = " . "'" . $this->user_id . "'"
		;
		if (query($checkQuery, "addToDB()")->fetch_array()) { // If a user already exists
			// Handle failure
			$output  = date("Y-m-d H:i:s T", time());
			$output .= " Could not add new user to database: user with user_id '";
			$output .= $this->user_id . "' already exists.\n";
			// Write to log file and kill process
			fwrite($log, $output, 2048);
			exit($output);
		} else { // If no such user exists

			// Insert where
			$insertQuery  = "
			INSERT INTO users
			(user_id
			,user_name)";

			// Insert what
			$insertQuery .= "
			VALUES ('" . $this->user_id . "'" .
				   ",'" . $this->user_name . "'";
			$insertQuery .= ");";

			query($insertQuery, "addToDB()");

			// Record success
			$output  = date("Y-m-d H:i:s T", time());
			$output .= " Added new user to database with user_id of '";
			$output .= $this->user_id;
			$output .= " and user_name" . $this->user_name . ".\n";
			fwrite($log, $output, 2048);

			// Get ID created for user in database
			$getIDResult = query("SELECT LAST_INSERT_ID()", "addToDB()");
			$getID       = $getIDResult->fetch_array()[0];

			// If user_id does not match ID created in database
			if ($this->user_id != $getID) {
		// Alert bad add
				$output  = date("Y-m-d H:i:s T", time());
				$output .= " Alert: user_id in array and user_id in database do not match. Changing user_id in array to '" . $getID . "'.\n";
				fwrite($log, $output, 2048);

		// Force user_id to match database
				$this->user_id = $getID;
			} else {
		// Record ID match
				$output  = date("Y-m-d H:i:s T", time());
				$output .= " Confirmed user_id in array (" . $this->user_id . ") matches user_id in database (" . $getID . ").\n";
				fwrite($log, $output, 2048);
			}
		}
	}

	/**
	 * Function deleteFromDB
	 *
	 * Removes du from the database if it finds one at its du_id.
	 *
	 * @todo finish conditions
	 * @global [$log | The open log file]
	 * @return void
	 */
	public function deleteFromDB() {
		global $log;

		// Check if there is a user with this new user's id to delete
		$checkQuery = "
		SELECT *
		FROM users
		WHERE user_id = '" . $this->user_id . "'"
		;
		if (query($checkQuery, "deleteFromDB()")->fetch_array()) { // If user exists
			$deleteQuery = "
			DELETE FROM users
			WHERE user_id = '" . $this->user_id . "'"
			;
				// Delete
			query($deleteQuery, "deleteFromDB()");

				// Record success
			$output  = date("Y-m-d H:i:s T", time());
			$output .= " Deleted user from database with user_id of '";
			$output .= $this->user_id . "'.\n";
			fwrite($log, $output, 2048);
			} else { // If no user is found
				// Handle failure
				$output  = date("Y-m-d H:i:s T", time());
				$output .= " Could not delete user from database: item with user_id '";
				$output .= $this->user_id . "' does not exist.\n";
				// Write to log file and kill process
				fwrite($log, $output, 2048);
				exit($output);
			}
		}

		public function getID() {
			return $this->user_id;
		}

		public function getUsername() {
			return $this->user_name;
		}
	}
	?>


text:
<?php

namespace Google\Service\CloudAsset;

class ConditionContext extends \Google\Model
{
  /**
   * @var string
   */
  public $accessTime;

  /**
   * @param string
   */
  public function setAccessTime($accessTime)
  {
    $this->accessTime = $accessTime;
  }
  /**
   * @return string
   */
  public function getAccessTime()
  {
    return $this->accessTime;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ConditionContext::class, 'Google_Service_CloudAsset_ConditionContext');


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>hrana super, dostava super, ma viste za 10</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/kung-food</Source>
</CrawlItem>


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.github.firenox89.shinobooru.ui.GoogleSignInActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Connect to Google Drive"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>


text:
// Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Tests for BottomNavbarStatusService.
 */

import { TestBed } from '@angular/core/testing';

import { BottomNavbarStatusService } from
  'services/bottom-navbar-status.service';
import { WindowDimensionsService } from
  'services/contextual/window-dimensions.service';

describe('BottomNavbarStatusService', () => {
  let bss: BottomNavbarStatusService = null;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [{
        provide: WindowDimensionsService,
        useValue: {
          isWindowNarrow: () => true,
          getWidth: () => 800
        }
      }]
    });

    bss = TestBed.get(BottomNavbarStatusService);
  });

  it('should have bottom navbar disabled by default', () => {
    expect(bss.bottomNavbarIsEnabled).toBe(false);
  });

  it('should have mark bottom navbar enabled', () => {
    bss.markBottomNavbarStatus(true);
    expect(bss.bottomNavbarIsEnabled).toBe(true);
  });

  it('should return if the bottom navbar is enabled', () => {
    expect(bss.isBottomNavbarEnabled()).toBe(false);
    bss.markBottomNavbarStatus(true);
    expect(bss.isBottomNavbarEnabled()).toBe(true);
  });
});


text:
@interface STViewsVC : STMainBaseVC

@end


text:
package org.apache.maven.model.plugin;

import java.util.List;

import javax.inject.Named;
import javax.inject.Singleton;

import org.apache.maven.model.Build;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.PluginManagement;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelProblemCollector;
import org.codehaus.plexus.util.xml.Xpp3Dom;

/**
 * Handles expansion of general build plugin configuration into individual executions.
 *
 * @author Benjamin Bentmann
 */
@Named
@Singleton
public class DefaultPluginConfigurationExpander
    implements PluginConfigurationExpander
{

    @Override
    public void expandPluginConfiguration( Model model, ModelBuildingRequest request, ModelProblemCollector problems )
    {
        Build build = model.getBuild();

        if ( build != null )
        {
            expand( build.getPlugins() );

            PluginManagement pluginManagement = build.getPluginManagement();

            if ( pluginManagement != null )
            {
                expand( pluginManagement.getPlugins() );
            }
        }
    }

    private void expand( List<Plugin> plugins )
    {
        for ( Plugin plugin : plugins )
        {
            Xpp3Dom pluginConfiguration = (Xpp3Dom) plugin.getConfiguration();

            if ( pluginConfiguration != null )
            {
                for ( PluginExecution execution : plugin.getExecutions() )
                {
                    Xpp3Dom executionConfiguration = (Xpp3Dom) execution.getConfiguration();

                    executionConfiguration =
                        Xpp3Dom.mergeXpp3Dom( executionConfiguration, new Xpp3Dom( pluginConfiguration ) );

                    execution.setConfiguration( executionConfiguration );
                }
            }
        }
    }

}


text:
void thread_init(int *info);
void thread_alloc(int *thread_id, int *info);
void thread_create(int *thread_id, int *attribute_id, void *(**routine)(void *),
                   void *argument, int* info);
void thread_join(int *thread_id, void **value_pointer, int *info);
void thread_cancel(int *thread_id, int *info);
void thread_exit(void *value_pointer);
void thread_destroy(int* info);

void thread_mutex_init(int *mutex_id, int *attribute_id, int *info);
void thread_mutex_lock(int *mutex_id, int *info);
void thread_mutex_unlock(int *mutex_id, int *info);
void thread_mutex_destroy(int *mutex_id, int *info);


text:
Individual
==========

.. automodule:: records

.. autoclass:: Individual
   :members:


text:
package org.eclipse.jnosql.mapping.graph.connections;

import com.arangodb.tinkerpop.gremlin.utils.ArangoDBConfigurationBuilder;
import jakarta.nosql.Settings;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.util.GraphFactory;
import org.eclipse.jnosql.mapping.graph.GraphConfiguration;

import java.util.Objects;

import static jakarta.nosql.Configurations.HOST;
import static jakarta.nosql.Configurations.PASSWORD;
import static jakarta.nosql.Configurations.USER;

/**
 * Creates the connection to {@link Graph} using ArangoDB.
 */
public class ArangoDB implements GraphConfiguration {

    private static final String EDGE = "arangodb.graph.edge";
    private static final String EDGE_CONFIGURATION = "arangodb.graph.edge.configuration";
    private static final String VERTEX = "arangodb.graph.vertex";
    private static final String GRAPH = "arangodb.graph.graph";

    @Override
    public Graph apply(Settings settings) {
        Objects.requireNonNull(settings, "settings is required");
        ArangoDBConfigurationBuilder builder = new ArangoDBConfigurationBuilder();

        settings.prefix(HOST.get())
                .stream()
                .map(Object::toString)
                .forEach(builder::arangoHosts);

        settings.prefix(VERTEX)
                .stream()
                .map(Object::toString)
                .forEach(builder::withVertexCollection);

        settings.prefix(EDGE)
                .stream()
                .map(Object::toString)
                .forEach(builder::withEdgeCollection);

        settings.get(USER.get())
                .map(Object::toString)
                .ifPresent(builder::arangoUser);

        settings.get(PASSWORD.get())
                .map(Object::toString)
                .ifPresent(builder::arangoPassword);

        settings.get(GRAPH)
                .map(Object::toString)
                .ifPresent(builder::graph);

        settings.prefix(EDGE_CONFIGURATION)
                .stream()
                .map(EdgeConfiguration::parse)
                .forEach(e -> e.add(builder));
        return GraphFactory.open(builder.build());
    }

    private static class EdgeConfiguration {

        private final String edge;

        private final String source;

        private final String target;

        private EdgeConfiguration(String source, String edge, String target) {
            this.edge = edge;
            this.source = source;
            this.target = target;
        }

        static EdgeConfiguration parse(Object value) {
            final String[] values = value.toString().split("\\|");
            if (values.length != 3) {
                throw new IllegalArgumentException("The element is valid it must have" +
                        " three element split by pipe: " + value);
            }
            return new EdgeConfiguration(values[0], values[1], values[2]);
        }

        private void add(ArangoDBConfigurationBuilder builder) {
            builder.configureEdge(edge, source, target);
        }
    }
}


text:
/**
 * @module ./rotten-tomato-service
 * @requires montage/core/core
 */
var Montage = require("montage/core/core").Montage;
var RangeController = require("montage/core/range-controller").RangeController;

var CategoryController = require("./category-controller").CategoryController;
var sharedTransport = require("./jsonp-transport").shared;

var API_KEY = "edvr96kp6mddwsasvmt269pw";
var BOX_OFFICE_FEED = "https://rottentomatoes.montagestudio.com/api/public/v1.0/lists/movies/box_office.json?limit=15&country=us&apikey=" + API_KEY;
var UPCOMING_FEED = "https://rottentomatoes.montagestudio.com/api/public/v1.0/lists/movies/upcoming.json?page_limit=30&page=1&country=us&apikey=" + API_KEY;
var TOP_RENTALS_FEED = "https://rottentomatoes.montagestudio.com/api/public/v1.0/lists/dvds/top_rentals.json?limit=20&country=us&apikey=" + API_KEY;
var IN_THEATERS_FEED = "https://rottentomatoes.montagestudio.com/api/public/v1.0/lists/movies/in_theaters.json?page_limit=30&page=1&country=us&apikey=" + API_KEY;

/**
 * @class RottenTomatoService
 * @extends Montage
 */
//TODO change to tomatoes
exports.RottenTomatoService = Montage.specialize(/** @lends RottenTomatoService# */ {
//TODO combine constructor and load
    constructor: {
        value: function RottenTomatoService() {
            this.super();
            this.categories = new RangeController().initWithContent([]);
            this.categories.avoidsEmptySelection = true;
        }
    },

    load: {
        value: function () {
            var self = this;

            self.latestBoxOffice = new CategoryController("Box Office", "box_office");
            self.upcoming = new CategoryController("Upcoming", "upcoming");
            self.topDvdRentals = new CategoryController("Rentals", "rentals");
            self.inTheaters = new CategoryController("In Theaters", "in_theaters");

            var boxOfficePromise = this.loadLatestBoxOfficeMovies()
            .then(function (latestBoxOffice) {
                self.latestBoxOffice.contentController.content = latestBoxOffice;
                self.categories.content.push(self.latestBoxOffice, self.inTheaters, self.upcoming, self.topDvdRentals);
                self.categories.select(self.latestBoxOffice);
            });
            // we fork the promise chain to expose the resolution of the first list.
            boxOfficePromise
            .then(function () {
                // then do the rest
                return [
                    self.loadUpcomingMovies(),
                    self.loadTopDvdRentals(),
                    self.loadInTheaters()
                ];
            })
            .spread(function (upcomingMovies, topDvdRentals, inTheaters) {
                self.upcoming.contentController.content = upcomingMovies;
                self.topDvdRentals.contentController.content = topDvdRentals;
                self.inTheaters.contentController.content = inTheaters;
            })
            .done();

            return boxOfficePromise;
        }
    },

    categories: {
        value: null
    },

    latestBoxOffice: {
        value: null
    },

    upcoming: {
        value: null
    },

    topDvdRentals: {
        value: null
    },

    inTheaters: {
        value: null
    },

    loadLatestBoxOfficeMovies: {
        value: function () {

            return sharedTransport.makeRequest(BOX_OFFICE_FEED, "rottenTomato")
            .then(function (response) {
                return response.movies;
            });
        }
    },

    loadUpcomingMovies: {
        value: function () {

            return sharedTransport.makeRequest(UPCOMING_FEED, "rottenTomato")
            .then(function (response) {
                return response.movies;
            });
        }
    },

    loadTopDvdRentals: {
        value: function () {

            return sharedTransport.makeRequest(TOP_RENTALS_FEED, "rottenTomato")
            .then(function (response) {
                return response.movies;
            });
        }

    },

    loadInTheaters: {
        value: function () {

            return sharedTransport.makeRequest(IN_THEATERS_FEED, "rottenTomato")
            .then(function (response) {
                return response.movies;
            });
        }
    }

});

exports.shared = new exports.RottenTomatoService();