text:
This is a minimal example of a jekyll site using the [jekyll-contentful gem](https://github.com/dommmel/jekyll-contentful) to pull content from contentful.com at build time.

The example also demos the i18n features of the gem.

## Running the example

At contentful.com

1. Create a contentful.com account and a space (if you don't have one already)
2. Add a the "de-DE" locale to the space (Settings -> Locales)
3. Create a content type "Article".
4. Add a short text field with the ID "title" to the content type. Make sure to check "This field represents the Entry title" and  "enable localization of this field" on the field's settings page.
5. Add a long text field with the ID "body". Check the checkbox "enable localization of this field" on the field's settings page.
4. Create at least one entry (better more, and preferably translate them as well)

On your machine

1. Clone the repo and ``cd`` into the folder
2. Change ``_config.yml`` to include your Contentful API keys, Space ID, Content Type ID
3. Run ``bundle install`` to install the dependencies
4. Run ``bundle exec jekyll serve -w`` to build and serve the site
5. Visit [http://127.0.0.1:4000](http://127.0.0.1:4000) to view the site you just built.

redpajama_set_name: RedPajamaGithub


text:
/**
* @file mingw.thread.h
* @brief std::thread implementation for MinGW
*
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER within this package.
*/

#ifndef WIN32STDTHREAD_H
#define WIN32STDTHREAD_H

#include <windows.h>
#include <functional>
#include <memory>
#include <chrono>
#include <system_error>
#include <process.h>

//instead of INVALID_HANDLE_VALUE _beginthreadex returns 0
#define _STD_THREAD_INVALID_HANDLE 0
namespace std
{

class thread
{
public:
    class id
    {
        DWORD mId;
        void clear() {mId = 0;}
        friend class thread;
    public:
        id(DWORD aId=0):mId(aId){}
        bool operator==(const id& other) const {return mId == other.mId;}
    };
protected:
    HANDLE mHandle;
    id mThreadId;
public:
    typedef HANDLE native_handle_type;
    id get_id() const noexcept {return mThreadId;}
    native_handle_type native_handle() const {return mHandle;}
    thread(): mHandle(_STD_THREAD_INVALID_HANDLE){}
    thread(thread& other)
    :mHandle(other.mHandle), mThreadId(other.mThreadId)
    {
        other.mHandle = _STD_THREAD_INVALID_HANDLE;
        other.mThreadId.clear();
    }
    template<class Function, class... Args>
    explicit thread(Function&& f, Args&&... args)
    {
        typedef decltype(std::bind(f, args...)) Call;
        Call* call = new Call(std::bind(f, args...));
        mHandle = (HANDLE)_beginthreadex(NULL, 0, threadfunc<Call>,
            (LPVOID)call, 0, (unsigned*)&(mThreadId.mId));
    }
    template <class Call>
    static unsigned int __stdcall threadfunc(void* arg)
    {
        std::unique_ptr<Call> upCall(static_cast<Call*>(arg));
        (*upCall)();
        return (unsigned long)0;
    }
    bool joinable() const {return mHandle != _STD_THREAD_INVALID_HANDLE;}
    void join()
    {
        if (get_id() == GetCurrentThreadId())
            throw system_error(EDEADLK, generic_category());
        if (mHandle == _STD_THREAD_INVALID_HANDLE)
            throw system_error(ESRCH, generic_category());
        if (!joinable())
            throw system_error(EINVAL, generic_category());
        WaitForSingleObject(mHandle, INFINITE);
        CloseHandle(mHandle);
        mHandle = _STD_THREAD_INVALID_HANDLE;
        mThreadId.clear();
    }

    ~thread()
    {
        if (joinable())
            std::terminate();
    }
    thread& operator=(const thread&) = delete;
    thread& operator=(thread&& other) noexcept
    {
        if (joinable())
          std::terminate();
        swap(std::forward<thread>(other));
        return *this;
    }
    void swap(thread&& other) noexcept
    {
        std::swap(mHandle, other.mHandle);
        std::swap(mThreadId.mId, other.mThreadId.mId);
    }
    static unsigned int hardware_concurrency() noexcept {return 1;}
    void detach()
    {
        if (!joinable())
            throw system_error();
        mHandle = _STD_THREAD_INVALID_HANDLE;
        mThreadId.clear();
    }
};
namespace this_thread
{
    inline thread::id get_id() {return thread::id(GetCurrentThreadId());}
    inline void yield() {Sleep(0);}
    template< class Rep, class Period >
    void sleep_for( const std::chrono::duration<Rep,Period>& sleep_duration)
    {
        Sleep(chrono::duration_cast<chrono::milliseconds>(sleep_duration).count());
    }
    template <class Clock, class Duration>
    void sleep_until(const std::chrono::time_point<Clock,Duration>& sleep_time)
    {
        sleep_for(sleep_time-Clock::now());
    }
}

}
#endif // WIN32STDTHREAD_H


text:
package org.springframework.boot.autoconfigure.condition;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.Environment;

/**
 * {@link Conditional} that checks if the specified properties have a specific value. By
 * default the properties must be present in the {@link Environment} and
 * not equal to {@code false}. The {@link #havingValue()} and
 * {@link #matchIfMissing()} attributes allow further customizations.
 *
 *

 * The {@link #havingValue} attribute can be used to specify the value that the property
 * should have. The table below shows when a condition matches according to the property
 * value and the {@link #havingValue()} attribute:
 *
 *

 *

 *

 * Property Value
 * {@code havingValue=""}
 * {@code havingValue="true"}
 * {@code havingValue="false"}
 * {@code havingValue="foo"}
 *

 *

 * {@code "true"}
 * yes
 * yes
 * no
 * no
 *

 *

 * {@code "false"}
 * no
 * no
 * yes
 * no
 *

 *

 * {@code "foo"}
 * yes
 * no
 * no
 * yes
 *

 *

 *
 *

 * If the property is not contained in the {@link Environment} at all, the
 * {@link #matchIfMissing()} attribute is consulted. By default missing attributes do not
 * match.
 *
 * @author Maciej Walkowiak
 * @author Stephane Nicoll
 * @author Phillip Webb
 * @since 1.1.0
 */
@Conditional(OnPropertyCondition.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface ConditionalOnProperty {

	/**
	 * Alias for {@link #name()}.
	 */
	String[] value() default {};

	/**
	 * A prefix that should be applied to each property. The prefix automatically ends
	 * with a dot if not specified.
	 */
	String prefix() default "";

	/**
	 * The name of the properties to test. If a prefix has been defined, it is applied to
	 * compute the full key of each property. For instance if the prefix is
	 * {@code app.config} and one value is {@code my-value}, the fully key would be
	 * {@code app.config.my-value}
	 *

	 * Use the dashed notation to specify each property, that is all lower case with a "-"
	 * to separate words (e.g. {@code my-long-property}).
	 */
	String[] name() default {};

	/**
	 * The string representation of the expected value for the properties. If not
	 * specified, the property must not be equals to {@code false}
	 */
	String havingValue() default "";

	/**
	 * Specify if the condition should match if the property is not set. Defaults to
	 * {@code false}
	 */
	boolean matchIfMissing() default false;

	/**
	 * If relaxed names should be checked. Defaults to {@code true}.
	 */
	boolean relaxedNames() default true;

}


text:
"""Utilities for working with meshes."""

import io

import trimesh

def serialize(mesh):
  mesh_str = trimesh.exchange.ply.export_ply(
      mesh, encoding='binary', vertex_normal=False)
  return mesh_str

def deserialize(mesh_str):
  mesh_ply_file_obj = io.BytesIO(mesh_str)
  mesh = trimesh.Trimesh(**trimesh.exchange.ply.load_ply(mesh_ply_file_obj))
  return mesh

def remove_small_components(mesh, min_volume=5e-05):
  """Removes all components with volume below the specified threshold."""
  if mesh.is_empty:
    return mesh
  out = [m for m in mesh.split(only_watertight=False) if m.volume > min_volume]
  if not out:
    return mesh
  return trimesh.util.concatenate(out)


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />

    <springProfile name="production">
        <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
        <appender name="StackRollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <File>/tmp/stackbox-demo.log</File>
            <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
                <FileNamePattern>/tmp/stackbox-demo.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
                <!-- 单个log文件大小 -->
                <maxFileSize>1MB</maxFileSize>
                <!-- 最多保存60份日志文件 -->
                <maxHistory>60</maxHistory>
                <!-- 日志文件总大小不超过20G -->
                <totalSizeCap>20GB</totalSizeCap>
            </rollingPolicy>
            <encoder>
                <Pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg %n</Pattern>
            </encoder>
        </appender>
    </springProfile>

    <springProfile name="development">
        <root level="INFO">
            <appender-ref ref="CONSOLE" />
        </root>
    </springProfile>

    <springProfile name="production">
    	<!-- 日志等级调成 debug 级别,以便看 rollingPolicy 中的设置是否生效 -->
        <root level="DEBUG">
            <appender-ref ref="CONSOLE" />
            <appender-ref ref="StackRollingFileAppender" />
        </root>
    </springProfile>

    <logger name="cn.stackbox.demo.controller" level="DEBUG"/>

</configuration>


text:
'use strict';
const _ = require('lodash');

/**
 * react2angular: Always wrap react components in an error boundary
 * Uses withErrorBoundary from core/presentation
 * @version 0.1.0
 */
const rule = function (context) {
  let coreImport;

  return {
    // Find an import from @spinnaker/core or core/presentation
    // This will be used to add the import for withErrorBoundary
    ImportDeclaration: function (node) {
      // import { foo, bar } from 'package';
      //                           ^^^^^^^
      const from = node.source.value || '';
      if (from === '@spinnaker/core') {
        coreImport = node;
      }
    },
    CallExpression: function (node) {
      // Find:
      // react2angular(SomeComponent, ...)
      const match = {
        type: 'CallExpression',
        callee: {
          type: 'Identifier',
          name: 'react2angular',
        },
      };

      if (!_.isMatch(node, match)) {
        return;
      }

      const r2aComponent = node.arguments[0];

      const wrappedInErrorBoundaryMatch = {
        type: 'CallExpression',
        callee: {
          type: 'Identifier',
          name: 'withErrorBoundary',
        },
      };

      // The react2angular component is already wrapped, nice!
      if (_.isMatch(r2aComponent, wrappedInErrorBoundaryMatch)) {
        return;
      }

      const message = `Wrap react2angular components in an error boundary using 'withErrorBoundary()'`;
      const filename = context.getFilename();
      const originalComponentSrc = context.getSourceCode().getText(r2aComponent);

      // Try to determine the angularjs component name
      // Look for component('angularComponentName', react2angular(ReactComponent, ....))
      //                    ^^^^^^^^^^^^^^^^^^^^^^

      const parentMatch = {
        type: 'CallExpression',
        callee: {
          property: {
            type: 'Identifier',
            name: 'component',
          },
        },
      };

      let componentName = `'react2angular component'`;
      const parentNode = node.parent;
      if (_.isMatch(parentNode, parentMatch)) {
        const [componentNameLiteralNode, arg2] = parentNode.arguments || [];
        if (arg2 === node && _.isMatch(componentNameLiteralNode, { type: 'Literal' })) {
          componentName = componentNameLiteralNode.raw;
        }
      }

      const fix = (fixer) => {
        const wrapped = `withErrorBoundary(${originalComponentSrc}, ${componentName})`;
        const insertErrorBoundary = fixer.replaceText(r2aComponent, wrapped);

        const fixes = [insertErrorBoundary];

        if (coreImport && coreImport.specifiers.length > 0) {
          // Append to the existing core/presentation or @spinnaker/core import
          const lastImport = coreImport.specifiers[coreImport.specifiers.length - 1];
          fixes.push(fixer.insertTextAfter(lastImport, `, withErrorBoundary`));
        } else {
          const importString = filename.includes('/modules/core/')
            ? 'core/presentation/SpinErrorBoundary'
            : '@spinnaker/core';
          fixes.push(fixer.insertTextBeforeRange([0, 0], `import { withErrorBoundary } from '${importString}';\n`));
        }
        return fixes;
      };

      context.report({ message, node, fix });
    },
  };
};

module.exports = {
  meta: {
    type: 'problem',
    docs: {
      description: `react2angular: Always wrap react components in an error boundary`,
    },
    fixable: 'code',
  },
  create: rule,
};


text:
<?php

namespace spec\Omniphx\Forrest\Providers\Laravel;

use Illuminate\Contracts\Events\Dispatcher as Event;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class LaravelEventSpec extends ObjectBehavior
{
    public function let(Event $event)
    {
        $this->beConstructedWith($event);
    }

    public function it_is_initializable()
    {
        $this->shouldHaveType('Omniphx\Forrest\Providers\Laravel\LaravelEvent');
    }

    public function it_should_fire_an_event(Event $event)
    {
        $event->dispatch(Argument::type('string'), Argument::type('array'), Argument::type('bool'))->shouldBeCalled();
        $this->fire('event',[]);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd">

	<!-- 注解 -->
	<context:component-scan base-package="com.xnx3">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	</context:component-scan>

	<aop:aspectj-autoproxy proxy-target-class="true"/>

</beans>


text:
package org.uiautomation.ios.server.instruments.communication.multi;

import org.libimobiledevice.ios.driver.binding.sdk.InstrumentsService;
import org.uiautomation.ios.server.command.UIAScriptRequest;
import org.uiautomation.ios.server.command.UIAScriptResponse;
import org.uiautomation.ios.server.instruments.communication.BaseCommunicationChannel;
import org.uiautomation.ios.server.instruments.communication.CommunicationChannel;

import java.util.logging.Logger;

public class MultiInstrumentsBasedCommunicationChannel extends BaseCommunicationChannel
    implements CommunicationChannel {

  private static final
  Logger
      log =
      Logger.getLogger(MultiInstrumentsBasedCommunicationChannel.class.getName());

  private final String sessionId;
  private final InstrumentsService instruments;

  public MultiInstrumentsBasedCommunicationChannel(int port, String aut, String sessionId,
                                                   InstrumentsService instruments) {
    super(sessionId);
    this.sessionId = sessionId;
    this.instruments = instruments;
  }

  @Override
  public UIAScriptResponse executeCommand(UIAScriptRequest request) {
    StringBuilder b = new StringBuilder();
    handleLastCommand(request);
    sendNextCommand(request);
    UIAScriptResponse response = waitForResponse();
    return response;
  }

  @Override
  public void stop() {
    //instruments.stopApp();
  }

  private void sendNextCommand(UIAScriptRequest r) {
    try {
      String
          templ =
          "UIATarget.localTarget().frontMostApp().setPreferencesValueForKey( '%s', 'cmd');";

      String escaped = r.getScript().replace("'", "\"");
      String script = String.format(templ, escaped);
      instruments.executeScriptNonManaged(script);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void handle(String message) {
    //System.out.println("MESSAGE : " + message);
    if (message.startsWith("IOS_DRIVER_RESPONSE:")) {

      String raw = message.replace("IOS_DRIVER_RESPONSE:", "");
      System.out.println(raw);
      UIAScriptResponse response = new UIAScriptResponse(raw);
      if (response.isFirstResponse()) {
        registerUIAScript();
      } else {
        setNextResponse(response);
      }
    } else {
      log(message);
    }
  }

  public void log(String message) {
    System.out.println(message);
  }
}


text:
"""
pip from http://pypi.python.org/pypi/pip
distribute from http://pypi.python.org/pypi/distribute
nose from http://pypi.python.org/pypi/nose/
virtualenv from http://pypi.python.org/pypi/virtualenv
"""

# on my system it is C:/temp/Projects/

# Create the basic Folder structure for a new skeleton project
"""
# $ mkdir projects
# $ cd projects/
$ mkdir skeleton
$ cd skeleton
$ mkdir bin NAME tests docs
"""

# upgrade PIP: From CMD prompt: python -m pip install -U pip

# install/upgrade 'Distribute': pip install setuptools-24.3.0-py2.py3-none-any.whl
# Wherever you saved the wheel download.

# Nose - deprecated.  Looking at Nose 2, pytest, or similar.

# pip list to show any/all packages and their version.

# virtualevn 15.0.2.

# To create a windows executable installer:  python setup.py bdist_wininst

# Need more PyCharm tutoring.  Really learn how to use the IDE>

# Django from scratch

# Flask tutorials

# Web2Py

# PyRamid  ?  :)


text:
import logging
import re

from google.appengine.api import memcache
from google.appengine.api import urlfetch

import tba_config

from datafeeds.datafeed_usfirst import DatafeedUsfirst
from datafeeds.usfirst_legacy_event_details_parser import UsfirstLegacyEventDetailsParser
from datafeeds.usfirst_legacy_event_teams_parser import UsfirstLegacyEventTeamsParser
from datafeeds.usfirst_legacy_team_details_parser import UsfirstLegacyTeamDetailsParser

from helpers.event_helper import EventHelper

from models.event import Event
from models.team import Team

class DatafeedUsfirstLegacy(DatafeedUsfirst):
    SESSION_KEY_GENERATING_PATTERN = "https://my.usfirst.org/myarea/index.lasso?event_type=FRC&year=%s"  # % (year)

    EVENT_DETAILS_URL_PATTERN = "https://my.usfirst.org/myarea/index.lasso?page=event_details&eid=%s"
    EVENT_TEAMS_URL_PATTERN = "https://my.usfirst.org/myarea/index.lasso?page=event_teamlist&results_size=250&eid=%s"
    TEAM_DETAILS_URL_PATTERN = "https://my.usfirst.org/myarea/index.lasso?page=team_details&tpid=%s"

    def __init__(self, *args, **kw):
        self._session_key = {}
        super(DatafeedUsfirstLegacy, self).__init__(*args, **kw)

    def getSessionKey(self, year):
        """
        Grab a page from FIRST so we can get a session key out the response header.
        """
        year = int(year)

        if self._session_key.get(year, False):
            return self._session_key.get(year)

        memcache_key = "usfirst_session_key_%s" % year
        session_key = memcache.get(memcache_key)
        if session_key is not None:
            self._session_key[year] = session_key
            return self._session_key.get(year)

        url = self.SESSION_KEY_GENERATING_PATTERN % year
        try:
            result = urlfetch.fetch(url, headers={'Referer': 'usfirst.org'}, deadline=10)
        except Exception, e:
            logging.error("URLFetch failed for: {}".format(url))
            logging.info(e)

            session_key = ''
            if tba_config.CONFIG["memcache"]:
                memcache.set(memcache_key, session_key, 60 * 5)
            self._session_key[year] = session_key
            return session_key

        if result.status_code == 200:
            session_key = result.headers.get('Set-Cookie', None)
            if session_key is not None:
                if tba_config.CONFIG["memcache"]:
                    memcache.set(memcache_key, session_key, 60 * 5)
                self._session_key[year] = session_key
                return self._session_key[year]
            logging.error('Unable to get USFIRST session key for %s.' % year)
            return None
        else:
            logging.error('HTTP code %s. Unable to retreive url: %s' %
                (result.status_code, self.SESSION_KEY_GENERATING_PATTERN))

    def getEventDetails(self, year, first_eid):
        if type(year) is not int:
            raise TypeError("year must be an integer")
        url = self.EVENT_DETAILS_URL_PATTERN % (first_eid)
        event, _ = self.parse(url, UsfirstLegacyEventDetailsParser, self.getSessionKey(year))
        if event is None:
            return None

        return Event(
            id=str(event["year"]) + str.lower(str(event["event_short"])),
            end_date=event.get("end_date", None),
            event_short=event.get("event_short", None),
            event_type_enum=event.get("event_type_enum", None),
            first_eid=first_eid,
            name=event.get("name", None),
            short_name=event.get("short_name", None),
            official=True,
            start_date=event.get("start_date", None),
            venue_address=event.get("venue_address", None),
            location=event.get("location", None),
            timezone_id=EventHelper.get_timezone_id(event.get("location", None), '{}{}'.format(event['year'], event['event_short'])),
            website=event.get("website", None),
            year=event.get("year", None)
        )

    def getEventTeams(self, year, first_eid):
        """
        Returns a list of team_numbers attending a particular Event
        """
        if type(year) is not int:
            raise TypeError("year must be an integer")
        url = self.EVENT_TEAMS_URL_PATTERN % (first_eid)
        teams, _ = self.parse(url, UsfirstLegacyEventTeamsParser, self.getSessionKey(year))
        if teams is None:
            return None

        return [Team(
            id="frc%s" % team.get("team_number", None),
            first_tpid=team.get("first_tpid", None),
            first_tpid_year=year,
            team_number=team.get("team_number", None)
            )
            for team in teams]

    def getTeamDetails(self, team):
        if hasattr(team, 'first_tpid'):
            if team.first_tpid:
                url = self.TEAM_DETAILS_URL_PATTERN % (team.first_tpid)
                team_dict, _ = self.parse(url, UsfirstLegacyTeamDetailsParser, self.getSessionKey(team.first_tpid_year))

                if team_dict is not None and "team_number" in team_dict:
                    return Team(
                        id="frc%s" % team_dict.get("team_number", None),
                        team_number=team_dict.get("team_number", None),
                        name=self._shorten(team_dict.get("name", None)),
                        address=team_dict.get("address", None),
                        nickname=team_dict.get("nickname", None),
                        website=team_dict.get("website", None),
                        rookie_year=team_dict.get("rookie_year", None),
                    )
                else:
                    logging.warning("No team_number found scraping %s, probably retired team" % team.team_number)
                    return None

        logging.warning('Null TPID for team %s' % team.team_number)
        return None


text:
using namespace Dogee;

template <typename T>
class ProducerConsumerQueue : public DObject
{
	DefBegin(DObject);
	Def(have_item, Ref<DSemaphore>);
	Def(have_place, Ref<DSemaphore>);
	Def(mutex, Ref<DSemaphore>);
	Def(size, int);
	Def(head, int);
	Def(tail, int);
	Def(buf, Array<T>);
public:
	DefEnd();
	ProducerConsumerQueue(ObjectKey obj_id) : DObject(obj_id)
	{
	}
	ProducerConsumerQueue(ObjectKey obj_id, int size) : DObject(obj_id)
	{
		self->size = size;
		self->head = 0;
		self->tail = 0;
		self->have_item = NewObj<DSemaphore>(0);
		self->have_place = NewObj<DSemaphore>(size);
		self->mutex = NewObj<DSemaphore>(1);
		self->buf = NewArray<T>(size);
	}

	void Produce(T val)
	{
		self->have_place->Acquire();
		self->mutex->Acquire();
		self->buf[tail] = val;
		self->tail = (self->tail + 1) % self->size;
		self->mutex->Release();
		self->have_item->Release();
	}
	T Consume()
	{
		self->have_item->Acquire();
		self->mutex->Acquire();
		T ret = self->buf[head];
		self->head = (self->head + 1) % self->size;
		self->mutex->Release();
		self->have_place->Release();
		return ret;
	}
	void Destory()
	{
		DelObj((Ref<DSemaphore>)self->have_item);
		DelObj((Ref<DSemaphore>)self->have_place);
		DelObj((Ref<DSemaphore>)self->mutex);
		DelArray((Array<T>)self->have_place);
	}
};

class Node : public DObject
{
	DefBegin(DObject);
public:
	Def(size, int);
	Def(data, int);
	Def(children, Array<Ref<Node>>);
	Node(ObjectKey obj_id) : DObject(obj_id)
	{
	}
};

DefGlobal(queue,Ref < ProducerConsumerQueue<Ref<Node>>>);
void WorkingThread(uint32_t param)
{
	for (;;)
	{
		Ref<Node> node = queue->Consume();
		for (int i = 0; i < node->size; i++)
		{
			queue->Produce(node->children[i]);
		}
	}
}
RegFunc(WorkingThread);

int main(int argc, char* argv[])
{
	HelperInitCluster(argc, argv);

	return 0;
}


text:
package org.jboss.weld.junit5.auto.interceptorAndDecorator;

import jakarta.enterprise.context.Dependent;

/**
 *
 * @author Matej Novotny
 */
@TestInterceptorBinding
@Dependent
public class InterceptedBean {

    public String ping() {
        return InterceptedBean.class.toString();
    }
}


text:
/* eslint-disable no-console */

'use strict';

const config = require('../knexfile');
const knex = require('knex')(config);

knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')
  .then(() => {
    return knex.schema.createTable('models', (t) => {
      t.uuid('id').primary().defaultTo(knex.raw('uuid_generate_v4()'));
      t.string('foo');
      t.string('bar');
      t.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
      t.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
      t.timestamp('deleted_at').nullable().defaultTo(null);
      t.boolean('is_deleted').notNullable().defaultTo(false);
    });
  })
  .then(() => {
    console.log('Done migrating');

    return knex.destroy();
  })
  .done();


text:
ASMJIT_BEGIN_SUB_NAMESPACE(x86)

//! \cond INTERNAL
//! \addtogroup asmjit_x86
//! \{

// ============================================================================
// [asmjit::x86::CallConvInternal]
// ============================================================================

//! X86-specific function API (calling conventions and other utilities).
namespace CallConvInternal {

//! Initialize `CallConv` structure (X86 specific).
Error init(CallConv& cc, uint32_t ccId, const Environment& environment) noexcept;

} // {CallConvInternal}

//! \}
//! \endcond

ASMJIT_END_SUB_NAMESPACE

#endif // ASMJIT_X86_X86CALLCONV_P_H_INCLUDED


text:
<!DOCTYPE html>

		<form action="user.js" method="post" target="_blank">
	  		Username: <input type="text" name="username" id="su_username">

	  		Password: <input type="password" name="password" id="su_password">

	  		e-mail: <input type="email" name="email"id="su_email">

	  		<input type="submit" value="Submit">
		</form>


text: LIFX Simple LAN Client


text:
#include <linux/device.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/nvmem-provider.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/slab.h>

struct ocotp_priv {
	struct device *dev;
	void __iomem *base;
	unsigned int nregs;
};

static int imx_ocotp_read(void *context, unsigned int offset,
			  void *val, size_t bytes)
{
	struct ocotp_priv *priv = context;
	unsigned int count;
	u32 *buf = val;
	int i;
	u32 index;

	index = offset >> 2;
	count = bytes >> 2;

	if (count > (priv->nregs - index))
		count = priv->nregs - index;

	for (i = index; i < (index + count); i++)
		*buf++ = readl(priv->base + 0x400 + i * 0x10);

	return 0;
}

static struct nvmem_config imx_ocotp_nvmem_config = {
	.name = "imx-ocotp",
	.read_only = true,
	.word_size = 4,
	.stride = 4,
	.owner = THIS_MODULE,
	.reg_read = imx_ocotp_read,
};

static const struct of_device_id imx_ocotp_dt_ids[] = {
	{ .compatible = "fsl,imx6q-ocotp",  (void *)128 },
	{ .compatible = "fsl,imx6sl-ocotp", (void *)32 },
	{ .compatible = "fsl,imx6sx-ocotp", (void *)128 },
	{ },
};
MODULE_DEVICE_TABLE(of, imx_ocotp_dt_ids);

static int imx_ocotp_probe(struct platform_device *pdev)
{
	const struct of_device_id *of_id;
	struct device *dev = &pdev->dev;
	struct resource *res;
	struct ocotp_priv *priv;
	struct nvmem_device *nvmem;

	priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
	if (!priv)
		return -ENOMEM;

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	priv->base = devm_ioremap_resource(dev, res);
	if (IS_ERR(priv->base))
		return PTR_ERR(priv->base);

	of_id = of_match_device(imx_ocotp_dt_ids, dev);
	priv->nregs = (unsigned int)of_id->data;
	imx_ocotp_nvmem_config.size = 4 * priv->nregs;
	imx_ocotp_nvmem_config.dev = dev;
	imx_ocotp_nvmem_config.priv = priv;
	nvmem = nvmem_register(&imx_ocotp_nvmem_config);
	if (IS_ERR(nvmem))
		return PTR_ERR(nvmem);

	platform_set_drvdata(pdev, nvmem);

	return 0;
}

static int imx_ocotp_remove(struct platform_device *pdev)
{
	struct nvmem_device *nvmem = platform_get_drvdata(pdev);

	return nvmem_unregister(nvmem);
}

static struct platform_driver imx_ocotp_driver = {
	.probe	= imx_ocotp_probe,
	.remove	= imx_ocotp_remove,
	.driver = {
		.name	= "imx_ocotp",
		.of_match_table = imx_ocotp_dt_ids,
	},
};
module_platform_driver(imx_ocotp_driver);

MODULE_AUTHOR("Philipp Zabel <p.zabel@pengutronix.de>");
MODULE_DESCRIPTION("i.MX6 OCOTP fuse box driver");
MODULE_LICENSE("GPL v2");


text:
The criteria for voter eligibility can be found in the [election guide](README.md).

**2022-09-19** - List generated from the [members](/org/members.yaml) file, and checking for at least one merged PR as noted by istio-policy-bot in the period 19 September 2021 to 19 September 2022.

If you feel you have standing in the Istio community but are not listed here, please fill in the [voting exception form](https://forms.gle/ucNfjUN6ruzJ3mL26). If your application is approved by a simple majority vote of the Steering Committee, you will be added.

- Aakash2017
- abhijoglekar
- AdamKorcz
- AllenZMC
- ameer00
- AndreaM12345
- andrewshaoyu
- angaluri
- Arhell
- aryan16
- bianpengyuan
- birkland
- cetezadi
- chaodaiG
- chases2
- Chen-Xintong
- christian-posta
- chizhg
- CloudJason
- cjwagner
- cnvergence
- costinm
- craigbox
- dapengJacky
- davidhauck
- dddddai
- deveshkandpal1224
- devincd
- djannot
- dgn
- dhawton
- douglas-reid
- drivebyer
- EItanya
- ejj
- eliavem
- ericvn
- fatedier
- feeltimeQ
- frankbu
- GregHanson
- gy95
- hanxiaop
- howardjohn
- hueifeng
- hzxuzhonghu
- ilevine
- ingwonsong
- irisdingbj
- jacob-delgado
- jasonwzm
- jewertow
- jmazzitelli
- jmunozro
- johnma14
- johnzheng1975
- jtischer-acasi
- jupblb
- justinpettit
- jwendell
- jzhupup
- kebe7jun
- kerthcet
- kdorosh
- kfaseela
- kinzhi
- Kmoneal
- kyessenov
- l8huang
- lambdai
- ldemailly
- lei-tang
- lgadban
- linsun
- litong01
- liwenhao0810
- louiscryan
- mandarjog
- mathetake
- Michelle951
- Monkeyanator
- morvencao
- my-git9
- myidpt
- nicole-lihui
- NiuYinlong1994
- nmittler
- nmnellis
- npolshakova
- nrjpoddar
- orangegzx
- ostromart
- PetrMc
- pinxiong
- PiotrSikora
- qfel
- rcernich
- richardwxn
- riita10069
- rinormaloku
- rrobb-aspen
- ruigulala
- rveerama1
- rvennam
- ryantking
- saltbo
- sergii-ssh
- shankgan
- Shikugawa
- shirleyyLi
- shivanshu1333
- shonecyx
- shriramsharma
- shuaijinchao
- silenceshell
- skyfirefrancisz
- SpecialYang
- stevenctl
- stewartbutler
- su225
- tbarrella
- therealmitchconnors
- thisisnotapril
- vikaschoudhary16
- vince-0202
- willowmck
- windsonsea
- wokeao
- wuwuwuyanz
- wzshiming
- xiaomudk
- xiaoyang-sde
- xichengliudui
- Xunzhuo
- yangminzhu
- yanrongshi
- yashykt
- ycai-aspen
- ydFu
- yingzhuivy
- ymesika
- YonkaFang
- youhonglian
- yskopets
- yuval-k
- yxxhero
- ZackButcher
- zackzhangkai
- zaunist
- zc2638
- zhaohuabing
- ZhengzheYang
- zhlsunshine
- zirain
- ZiyangXiao
- zouyee


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.VisualStudio.Editor.Mocks
{
    [ExcludeFromCodeCoverage]
    public sealed class TextViewModelMock : ITextViewModel
    {
        public TextViewModelMock(ITextBuffer textBuffer)
        {
            DataBuffer = textBuffer;
            EditBuffer = textBuffer;
            VisualBuffer = textBuffer;
            DataModel = new TextDataModelMock(textBuffer);
        }

        public ITextBuffer DataBuffer { get; private set; }

        public ITextDataModel DataModel { get; private set; }

        public ITextBuffer EditBuffer { get; private set; }

        public PropertyCollection Properties { get; private set; } = new PropertyCollection();

        public ITextBuffer VisualBuffer { get; private set; }

        public void Dispose()
        {
        }

        public SnapshotPoint GetNearestPointInVisualBuffer(SnapshotPoint editBufferPoint)
        {
            throw new NotImplementedException();
        }

        public SnapshotPoint GetNearestPointInVisualSnapshot(SnapshotPoint editBufferPoint, ITextSnapshot targetVisualSnapshot, PointTrackingMode trackingMode)
        {
            throw new NotImplementedException();
        }

        public bool IsPointInVisualBuffer(SnapshotPoint editBufferPoint, PositionAffinity affinity)
        {
            return true;
        }
    }
}


text:
    <kc-tabs-realm></kc-tabs-realm>

{{:: 'initial-access-tokens' | translate}}

{{:: 'client-reg-policies' | translate}}

    <form class="form-horizontal" name="realmForm" novalidate kc-read-only="!access.manageRealm">

        <fieldset>
            <legend>{{:: 'anonymous-policies' | translate}}</legend><kc-tooltip>{{:: 'anonymous-policies.tooltip' | translate}}</kc-tooltip>

 0 && access.manageClients">

                                <select class="form-control" ng-model="selectedProvider"
                                        ng-options="p.id for p in providers"
                                        data-ng-change="addProvider('anonymous', selectedProvider); selectedProvider = null">
                                    <option value="" disabled selected>{{:: 'add-provider.placeholder' | translate}}</option>
                                </select>

 0">
                    {{:: 'policy-name' | translate}}
                    {{:: 'provider-id' | translate}}
                    {{:: 'actions' | translate}}

                    {{instance.name}}
                    {{instance.providerId}}
                    {{:: 'edit' | translate}}
                    {{:: 'delete' | translate}}

                    {{:: 'no-client-reg-policies-configured' | translate}}

        </fieldset>

        <fieldset>
            <legend>{{:: 'auth-policies' | translate}}</legend><kc-tooltip>{{:: 'auth-policies.tooltip' | translate}}</kc-tooltip>

 0 && access.manageClients">

                                <select class="form-control" ng-model="selectedProvider"
                                        ng-options="p.id for p in providers"
                                        data-ng-change="addProvider('authenticated', selectedProvider); selectedProvider = null">
                                    <option value="" disabled selected>{{:: 'add-provider.placeholder' | translate}}</option>
                                </select>

 0">
                    {{:: 'policy-name' | translate}}
                    {{:: 'provider-id' | translate}}
                    {{:: 'actions' | translate}}

                    {{instance.name}}
                    {{instance.providerId}}
                    {{:: 'edit' | translate}}
                    {{:: 'delete' | translate}}

                    {{:: 'no-client-reg-policies-configured' | translate}}

        </fieldset>

    </form>

<kc-menu></kc-menu>


text:
<!DOCTYPE html>

  <title>Onde Latte To Go - Dev</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href='http://fonts.googleapis.com/css?family=Roboto:400,300,500' rel='stylesheet' type='text/css'>


text:
package com.guangzhou.gov.view;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.guangzhou.gov.R;
import com.guangzhou.gov.manager.UserManager;
import com.guangzhou.gov.net.bean.ApplyInfo;
import com.guangzhou.gov.net.bean.BaseBean;
import com.guangzhou.gov.net.bean.request.Request;
import com.guangzhou.gov.net.http.Http;
import com.guangzhou.gov.net.http.HttpListener;
import com.guangzhou.gov.net.http.HttpStatus;
import com.guangzhou.gov.util.Constant;
import com.guangzhou.gov.util.LogUtils;

/**
 *
 * @author chenjianping
 *
 */
public class ShengbanView extends FrameLayout implements OnClickListener, HttpListener
{
	private VerificationActivity mContext;
	private ShengbanNextView mShengbanNextView;
	public ShengbanView(VerificationActivity context, ShengbanNextView v)
	{
		super(context);
		mContext = context;
		mShengbanNextView = v;
		setBackgroundColor(Color.WHITE);
		addmTitle();
		addInfoView();
	}

	public static final int TITLE_H = ViewUtils.getPXByHeight(126);
	private TextView mTitle;
	private void addmTitle() {
		mTitle = new TextView(mContext);
		mTitle.setTextColor(Constant.sBlack54Color);
		mTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, ViewUtils.getPXByWidth(48));
		mTitle.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
		mTitle.setText(R.string.shengbanren_info);
		Drawable a = getResources().getDrawable(R.drawable.head);
		a.setBounds(0, 0, ViewUtils.getPXByHeight(168), ViewUtils.getPXByHeight(126));
		mTitle.setCompoundDrawables(a, null, null, null);
		//mTitle.setCompoundDrawablePadding(OnlineAffairsView.LEFT_MARGIN);
		//mTitle.setPadding(OnlineAffairsView.LEFT_MARGIN, 0, 0, 0);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, TITLE_H, Gravity.TOP);
        mTitle.setBackgroundColor(Constant.sTitle3BgColor);
        addView(mTitle, params);

        View v = new View(mContext);
		LayoutParams params1 = new LayoutParams(LayoutParams.MATCH_PARENT, 1, Gravity.TOP);
		params1.topMargin = TITLE_H;
        v.setBackgroundColor(Constant.sBlack10Color);
        addView(v, params1);
	}

	private LinearLayout mInfoLy;
	private LayoutInflater mInflater;
	private void addInfoView() {
		mInflater = LayoutInflater.from(mContext);
		View mGallery = mInflater.inflate(R.layout.post_data_ly, this, false);
		mInfoLy = (LinearLayout) mGallery.findViewById(R.id.info_ly);
		LayoutParams mParams = new LayoutParams(Constant.sRealWidth - OnlineAffairsView.LEFT_MARGIN * 2,
				ViewUtils.getPXByHeight(1110), Gravity.TOP | Gravity.CENTER_HORIZONTAL);
		mParams.topMargin = TITLE_H;
		addView(mGallery, mParams);
		//mGallery.setBackgroundColor(0x33000000);

		initUserData();
		addInfo2InfoLy();
		addComfirmBtn();
	}

	private EditText[] mEditTexts;
	private void addInfo2InfoLy() {
		mEditTexts = new EditText[DATA_NAME.length];
		for (int i = 0; i < DATA_NAME.length; i++) {
			LinearLayout itemView = new LinearLayout(mContext);
			itemView.setOrientation(LinearLayout.HORIZONTAL);
			itemView.setGravity(Gravity.CENTER_VERTICAL);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
					ViewUtils.getPXByHeight(144));
			itemView.setLayoutParams(params);
			itemView.setPadding(OnlineAffairsView.LEFT_MARGIN, OnlineAffairsView.LEFT_MARGIN / 2,
					OnlineAffairsView.LEFT_MARGIN, OnlineAffairsView.LEFT_MARGIN / 2);
			mInfoLy.addView(itemView, params);

			TextView department = new TextView(mContext);
			department.setTag("department");
			department.setTextSize(TypedValue.COMPLEX_UNIT_PX,
					ViewUtils.getPXByWidth(42));
			department.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);

			LinearLayout.LayoutParams timeParams = new LinearLayout.LayoutParams(
					ViewUtils.getPXByWidth(220), LayoutParams.WRAP_CONTENT);
			timeParams.gravity = Gravity.FILL_HORIZONTAL | Gravity.CENTER_VERTICAL;
			itemView.addView(department, timeParams);
			department.setTextColor(Constant.sBlack54Color);
			department.setText(DATA_NAME[i]);

			mEditTexts[i] = new EditText(mContext);
			mEditTexts[i].setTag("info");
			mEditTexts[i].setTextSize(TypedValue.COMPLEX_UNIT_PX,
					ViewUtils.getPXByWidth(48));
			mEditTexts[i].setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			mEditTexts[i].setBackgroundResource(R.drawable.login_edittext_indicator);
			int padding = ViewUtils.getPXByWidth(15);
			mEditTexts[i].setPadding(padding, 0, padding, 0);
			LinearLayout.LayoutParams infoParams = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			infoParams.leftMargin = padding;
			itemView.addView(mEditTexts[i], infoParams);

			if (i < COULD_MODIFY_INDEX) {
				mEditTexts[i].setFocusableInTouchMode(false);
				mEditTexts[i].setFocusable(false);
				mEditTexts[i].setTextColor(Constant.sBlack54Color);
			} else {
				mEditTexts[i].setFocusableInTouchMode(true);
				mEditTexts[i].setFocusable(true);
				mEditTexts[i].setTextColor(Constant.sBlack87Color);
				if (i == COULD_MODIFY_INDEX + 1 ||
						i == COULD_MODIFY_INDEX + 2) {
					mEditTexts[i].setInputType(InputType.TYPE_CLASS_PHONE);
				}
			}

			if (sUserInfo != null) {
				mEditTexts[i].setText(sUserInfo[i]);
			}
		}
	}

	private Button mConfirm;
	public static final int BTN_H = ViewUtils.getPXByHeight(280);
	private void addComfirmBtn() {
		LinearLayout mBottomLy = new LinearLayout(mContext);
		mBottomLy.setOrientation(LinearLayout.HORIZONTAL);
		mBottomLy.setGravity(Gravity.CENTER);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				BTN_H, Gravity.BOTTOM);
		addView(mBottomLy, params);
		mBottomLy.setBackgroundColor(Constant.sTitle3BgColor);

		mConfirm = new Button(mContext);
		mConfirm.setBackgroundResource(R.drawable.yellow_btn_indicator);
		mConfirm.setOnClickListener(this);
		LinearLayout.LayoutParams timeParams = new LinearLayout.LayoutParams(
				ViewUtils.getPXByWidth(500), ViewUtils.getPXByHeight(126));
		timeParams.gravity = Gravity.CENTER;
		mConfirm.setText("下一步");
		mConfirm.setTextSize(TypedValue.COMPLEX_UNIT_PX,
				ViewUtils.getPXByWidth(48));
		mConfirm.setTextColor(Color.WHITE);
		mBottomLy.addView(mConfirm, timeParams);

	}

	private Http mHttp;
	@Override
	public void onClick(View v)
	{
		//test for network error
		/*this.setVisibility(INVISIBLE);
		mShengbanNextView.setVisibility(VISIBLE);*/

		if (mConfirm == v && mShengbanNextView != null) {
			for (int i = 0; i < DATA_NAME.length; i++) {
				sUserInfo[i] = mEditTexts[i].getText().toString();
				LogUtils.log(null, "sUserInfo[i] = " + sUserInfo[i]);
			}
			for (int i = COULD_MODIFY_INDEX; i < DATA_NAME.length; i++) {
				if (sUserInfo[i].length() <= 0) {
					/*Toast toast = Toast.makeText(mContext, DATA_NAME[i] +
						     "不能为空" , Toast.LENGTH_LONG);
						   toast.setGravity(Gravity.CENTER, 0, 0);
						   toast.show();*/
					MyToast.showToast(mContext, DATA_NAME[i] +
						     "不能为空");
					return;
				}
			}

			mHttp = new Http(mContext);
			mHttp.setHttpListener(this);
			mHttp.doCommitDoc("正在提交...", ShengbanNextView.APPOVE_ITEM_STUFF_ID[VerificationActivity.sIndex][0][0],
					sUserInfo[0], sUserInfo[1], sUserInfo[2],
					sUserInfo[3], sUserInfo[4 ], sUserInfo[5], sUserInfo[6]);
		}
	}

	public static Request getOuterNetDataInfo(String[] commitInfo)
    {
        Request r = new Request();
        ApplyInfo info = new ApplyInfo();
        info.setOperateStep("recheck");
        info.setIsSaveTemp("true");
        info.setActionFlag("dosave");
        info.setApproveItem("4711");
        if (UserManager.getInstance().mUser != null) {
            info.setUser_code(UserManager.getInstance().mUser.getUserInfo().getU_name());
        }

        info.setCust_contact_person(commitInfo[COULD_MODIFY_INDEX + 0]);
        info.setCustMobile(commitInfo[COULD_MODIFY_INDEX + 1]);
        info.setCust_contact_way(commitInfo[COULD_MODIFY_INDEX + 2]);
        info.setCust_name(commitInfo[COULD_MODIFY_INDEX + 3]);
        r.setOuterNetDataInfo(info);
        return r;
    }

	private static final int COULD_MODIFY_INDEX = 3;
	private final static String[] DATA_NAME = {
		"企业名称:", "企业地址:", "企业类型:",
		"经办人:", "手机:",  "电话:", "项目名称:",
	};

	public static String[] sUserInfo;
	private void initUserData() {
		sUserInfo = new String[DATA_NAME.length];
		if (UserManager.getInstance().mUser != null && UserManager.getInstance().mUser.getUserInfo() != null) {
			/*1.企业类型,需要转义:
			"type":"p1",type,--如果是个人用户:p1为男,p0为女。 如果是企业用户:e1国有,e2民营,e3外资,e4港澳台资,e5其他
			2.经办人姓名:handler_name
			3.经办人手机:mobile_phone*/
			sUserInfo[0] = UserManager.getInstance().mUser.getUserInfo().getName();
			sUserInfo[1] = UserManager.getInstance().mUser.getUserInfo().getAddress();
			sUserInfo[2] = translateType(UserManager.getInstance().mUser.getUserInfo().getType());
			sUserInfo[3] = UserManager.getInstance().mUser.getUserInfo().getHandler_name();
			sUserInfo[4] = UserManager.getInstance().mUser.getUserInfo().getMobile_phone();
			sUserInfo[5] = UserManager.getInstance().mUser.getUserInfo().getTel_phone();
			//sUserInfo[6] = UserManager.getInstance().mUser.getUserInfo().getName();
		}
	}

	private String translateType(String type) {
		/*1.企业类型,需要转义:
		"type":"p1",type,--如果是个人用户:p1为男,p0为女。 如果是企业用户:e1国有,e2民营,e3外资,e4港澳台资,e5其他*/
		String ret = "其他";
		if (type.equalsIgnoreCase("p1")) {
			ret = "男";
		} else if (type.equalsIgnoreCase("p0")) {
			ret = "女";
		} else if (type.equalsIgnoreCase("e1")) {
			ret = "国有";
		} else if (type.equalsIgnoreCase("e2")) {
			ret = "民营";
		} else if (type.equalsIgnoreCase("e3")) {
			ret = "外资";
		} else if (type.equalsIgnoreCase("e4")) {
			ret = "港澳台资";
		} else  if (type.equalsIgnoreCase("e5")) {
			ret = "其他";
		}

		return ret;
	}

	@Override
	public void onSuccess(Object parent, HttpStatus mStatus) {
		LogUtils.log(null, "Shengban Step1: onSuccess");

		//判断流水号
		if (((BaseBean)parent).getControlSeq() != null && ((BaseBean)parent).getControlSeq().length() > 0)
		{
			this.setVisibility(INVISIBLE);
			mShengbanNextView.setVisibility(VISIBLE);
			mShengbanNextView.setBaseBean((BaseBean)parent);
		} else {
			/*Toast toast = Toast.makeText(mContext, "流水号错误, 请重试 ",
					Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();*/
			MyToast.showToast(mContext, "流水号错误, 请重试 ");
		}
	}

	@Override
	public void onHttpError(HttpStatus mHs) {

		/*Toast toast = Toast.makeText(mContext, "请检查您的网络连接" + mHs.error,
				Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();*/
		MyToast.showToast(mContext,  "请检查您的网络连接" + mHs.error);
	}

	@Override
	public void onFail(HttpStatus mHs) {

		String msg = mHs.error;
		if (mHs.error.length() < 1) {
			msg = "提交失败,请检查网络";
		}
		MyToast.showToast(mContext,  msg);
		LogUtils.log(null, "HttpStatus.ERROR_CODE.LoginExpired =" + HttpStatus.ERROR_CODE.LoginExpired.getValue());
		 if (mHs.error_code.equals("" + HttpStatus.ERROR_CODE.LoginExpired.getValue())) {
			 Intent intent = new Intent();
				intent.putExtra(Tab3Activity.CLOSE_TAG, true);
				intent.putExtra(Tab3Activity.LOGIN_TAG, true);
				intent.setClass(mContext, Tab3Activity.class);
				mContext.startActivity(intent);
				mContext.finish();
		 }
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, SimpleAdapterActivity!</string>
    <string name="app_name">ExampleAdapters</string>
    <string name="tv_cancion">Canción</string>
    <string name="tv_reproducciones">8 reproducciones</string>
    <string name="title_activity_lista_clase4">ListaClase4</string>
    <string name="hello_world">Hello world!</string>
    <string name="lb_ejemplo_clase">Ejemplo Clase 4</string>
    <string name="lb_btn_ejemplo">Ejemplo Clase</string>
    <string name="title_activity_adapter_personalizado_clase4">AdapterPersonalizadoClase4</string>
    <string name="title_activity_lista_reproduccion">ListaReproduccion</string>

</resources>


text:
require 'spec_helper'

describe Bitbucket::Representation::PullRequestComment do
  describe '#iid' do
    it { expect(described_class.new('id' => 1).iid).to eq(1) }
  end

  describe '#file_path' do
    it { expect(described_class.new('inline' => { 'path' => '/path' }).file_path).to eq('/path') }
  end

  describe '#old_pos' do
    it { expect(described_class.new('inline' => { 'from' => 3 }).old_pos).to eq(3) }
  end

  describe '#new_pos' do
    it { expect(described_class.new('inline' => { 'to' => 3 }).new_pos).to eq(3) }
  end

  describe '#parent_id' do
    it { expect(described_class.new({ 'parent' => { 'id' => 2 } }).parent_id).to eq(2) }
    it { expect(described_class.new({}).parent_id).to be_nil }
  end

  describe '#inline?' do
    it { expect(described_class.new('inline' => {}).inline?).to be_truthy }
    it { expect(described_class.new({}).inline?).to be_falsey }
  end

  describe '#has_parent?' do
    it { expect(described_class.new('parent' => {}).has_parent?).to be_truthy }
    it { expect(described_class.new({}).has_parent?).to be_falsey }
  end
end


text:
class AutomationBrowserTracker;
class AutomationResourceMessageFilter;
class AutomationTabTracker;
class AutomationWindowTracker;
class Browser;
class ExternalTabContainer;
class FindInPageNotificationObserver;
class InitialLoadObserver;
class LoginHandler;
class MetricEventDurationObserver;
class NavigationControllerRestoredObserver;
class NewTabUILoadObserver;
class Profile;
struct AutomationMsg_Find_Params;
struct Reposition_Params;
struct ExternalTabSettings;

namespace IPC {
class ChannelProxy;
}

namespace content {
class NavigationController;
class RenderViewHost;
}

namespace base {
class DictionaryValue;
}

namespace content {
class DownloadItem;
class WebContents;
}

namespace gfx {
class Point;
}

class AutomationProvider
    : public IPC::Listener,
      public IPC::Sender,
      public base::SupportsWeakPtr<AutomationProvider>,
      public base::RefCountedThreadSafe<
          AutomationProvider, content::BrowserThread::DeleteOnUIThread>,
      public content::TraceSubscriber {
 public:
  explicit AutomationProvider(Profile* profile);

  Profile* profile() const { return profile_; }

  void set_profile(Profile* profile);

  // Initializes a channel for a connection to an AutomationProxy.
  // If channel_id starts with kNamedInterfacePrefix, it will act
  // as a server, create a named IPC socket with channel_id as its
  // path, and will listen on the socket for incoming connections.
  // If channel_id does not, it will act as a client and establish
  // a connection on its primary IPC channel. See ipc/ipc_channel_posix.cc
  // for more information about kPrimaryIPCChannel.
  bool InitializeChannel(const std::string& channel_id) WARN_UNUSED_RESULT;

  virtual IPC::Channel::Mode GetChannelMode(bool use_named_interface);

  // Sets the number of tabs that we expect; when this number of tabs has
  // loaded, an AutomationMsg_InitialLoadsComplete message is sent.
  void SetExpectedTabCount(size_t expected_tabs);

  // Called when the inital set of tabs has finished loading.
  // Call SetExpectedTabCount(0) to set this to true immediately.
  void OnInitialTabLoadsComplete();

  // Called when the ChromeOS network library has finished its first update.
  void OnNetworkLibraryInit();

  // Called when the chromeos WebUI OOBE/Login is ready.
  void OnOOBEWebuiReady();

  // Checks all of the initial load conditions, then sends the
  // InitialLoadsComplete message over the automation channel.
  void SendInitialLoadMessage();

  // Call this before calling InitializeChannel. If called, send the
  // InitialLoadsComplete message immediately when the automation channel is
  // connected, without waiting for the initial load conditions to be met.
  void DisableInitialLoadObservers();

  // Get the index of a particular NavigationController object
  // in the given parent window.  This method uses
  // TabStrip::GetIndexForNavigationController to get the index.
  int GetIndexForNavigationController(
      const content::NavigationController* controller,
      const Browser* parent) const;

  // IPC::Sender implementation.
  virtual bool Send(IPC::Message* msg) OVERRIDE;

  // IPC::Listener implementation.
  virtual void OnChannelConnected(int pid) OVERRIDE;
  virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
  virtual void OnChannelError() OVERRIDE;

  IPC::Message* reply_message_release() {
    IPC::Message* reply_message = reply_message_;
    reply_message_ = NULL;
    return reply_message;
  }

#if defined(OS_WIN)
  // Adds the external tab passed in to the tab tracker.
  bool AddExternalTab(ExternalTabContainer* external_tab);
#endif

  // Get the DictionaryValue equivalent for a download item. Caller owns the
  // DictionaryValue.
  base::DictionaryValue* GetDictionaryFromDownloadItem(
      const content::DownloadItem* download,
      bool incognito);

 protected:
  friend struct content::BrowserThread::DeleteOnThread<
      content::BrowserThread::UI>;
  friend class base::DeleteHelper<AutomationProvider>;
  virtual ~AutomationProvider();

  // Helper function to find the browser window that contains a given
  // NavigationController and activate that tab.
  // Returns the Browser if found.
  Browser* FindAndActivateTab(content::NavigationController* contents);

  // Convert a tab handle into a WebContents. If |tab| is non-NULL a pointer
  // to the tab is also returned. Returns NULL in case of failure or if the tab
  // is not of the WebContents type.
  content::WebContents* GetWebContentsForHandle(
      int handle, content::NavigationController** tab);

  // Returns the protocol version which typically is the module version.
  virtual std::string GetProtocolVersion();

  // Returns the associated view for the tab handle passed in.
  // Returns NULL on failure.
  content::RenderViewHost* GetViewForTab(int tab_handle);

  // Called on IPC message deserialization failure. Prints an error message
  // and closes the IPC channel.
  void OnMessageDeserializationFailure();

  scoped_ptr<AutomationBrowserTracker> browser_tracker_;
  scoped_ptr<InitialLoadObserver> initial_load_observer_;
  scoped_ptr<MetricEventDurationObserver> metric_event_duration_observer_;
  scoped_ptr<AutomationTabTracker> tab_tracker_;
  scoped_ptr<AutomationWindowTracker> window_tracker_;

  Profile* profile_;

  // A pointer to reply message used when we do asynchronous processing in the
  // message handler.
  // TODO(phajdan.jr): Remove |reply_message_|, it is error-prone.
  IPC::Message* reply_message_;

  // Consumer for asynchronous history queries.
  CancelableRequestConsumer consumer_;

  // Sends a find request for a given query.
  void SendFindRequest(
      content::WebContents* web_contents,
      bool with_json,
      const string16& search_string,
      bool forward,
      bool match_case,
      bool find_next,
      IPC::Message* reply_message);

  scoped_refptr<AutomationResourceMessageFilter>
      automation_resource_message_filter_;

  // True iff we should open a new automation IPC channel if it closes.
  bool reinitialize_on_channel_error_;

 private:
  // Storage for EndTracing() to resume operations after a callback.
  struct TracingData {
    std::list<std::string> trace_output;
    scoped_ptr<IPC::Message> reply_message;
  };

  // TraceSubscriber:
  virtual void OnEndTracingComplete() OVERRIDE;
  virtual void OnTraceDataCollected(
      const scoped_refptr<base::RefCountedString>& trace_fragment) OVERRIDE;

  void OnUnhandledMessage(const IPC::Message& message);

  // Clear and reinitialize the automation IPC channel.
  bool ReinitializeChannel();

  void HandleUnused(const IPC::Message& message, int handle);
  void GetFilteredInetHitCount(int* hit_count);
  void SetProxyConfig(const std::string& new_proxy_config);

  // Responds to the FindInPage request, retrieves the search query parameters,
  // launches an observer to listen for results and issues a StartFind request.
  void HandleFindRequest(int handle,
                         const AutomationMsg_Find_Params& params,
                         IPC::Message* reply_message);

  void OnSetPageFontSize(int tab_handle, int font_size);

  // See browsing_data_remover.h for explanation of bitmap fields.
  void RemoveBrowsingData(int remove_mask);

  // Notify the JavaScript engine in the render to change its parameters
  // while performing stress testing. See
  // |ViewHostMsg_JavaScriptStressTestControl_Commands| in render_messages.h
  // for information on the arguments.
  void JavaScriptStressTestControl(int handle, int cmd, int param);

  void BeginTracing(const std::string& category_patterns, bool* success);
  void EndTracing(IPC::Message* reply_message);
  void GetTracingOutput(std::string* chunk, bool* success);

  // Asynchronous request for printing the current tab.
  void PrintAsync(int tab_handle);

  // Uses the specified encoding to override the encoding of the page in the
  // specified tab.
  void OverrideEncoding(int tab_handle,
                        const std::string& encoding_name,
                        bool* success);

  // Selects all contents on the page.
  void SelectAll(int tab_handle);

  // Edit operations on the page.
  void Cut(int tab_handle);
  void Copy(int tab_handle);
  void Paste(int tab_handle);

  void KeyPress(int tab_handle, int key);

  void ReloadAsync(int tab_handle);
  void StopAsync(int tab_handle);
  void SaveAsAsync(int tab_handle);

  // Method called by the popup menu tracker when a popup menu is opened.
  void NotifyPopupMenuOpened();

#if defined(OS_WIN)
  // The functions in this block are for use with external tabs, so they are
  // Windows only.

  // The container of an externally hosted tab calls this to reflect any
  // accelerator keys that it did not process. This gives the tab a chance
  // to handle the keys
  void ProcessUnhandledAccelerator(const IPC::Message& message, int handle,
                                   const MSG& msg);

  void SetInitialFocus(const IPC::Message& message, int handle, bool reverse,
                       bool restore_focus_to_view);

  void OnTabReposition(int tab_handle,
                       const Reposition_Params& params);

  void OnForwardContextMenuCommandToChrome(int tab_handle, int command);

  void CreateExternalTab(const ExternalTabSettings& settings,
                         HWND* tab_container_window,
                         HWND* tab_window,
                         int* tab_handle,
                         int* session_id);

  void ConnectExternalTab(uint64 cookie,
                          bool allow,
                          HWND parent_window,
                          HWND* tab_container_window,
                          HWND* tab_window,
                          int* tab_handle,
                          int* session_id);

  void NavigateInExternalTab(
      int handle, const GURL& url, const GURL& referrer,
      AutomationMsg_NavigationResponseValues* status);
  void NavigateExternalTabAtIndex(
      int handle, int index, AutomationMsg_NavigationResponseValues* status);

  // Handler for a message sent by the automation client.
  void OnMessageFromExternalHost(int handle, const std::string& message,
                                 const std::string& origin,
                                 const std::string& target);

  void OnBrowserMoved(int handle);

  void OnRunUnloadHandlers(int handle, IPC::Message* reply_message);

  void OnSetZoomLevel(int handle, int zoom_level);

  ExternalTabContainer* GetExternalTabForHandle(int handle);
#endif  // defined(OS_WIN)

  scoped_ptr<IPC::ChannelProxy> channel_;
  scoped_ptr<NewTabUILoadObserver> new_tab_ui_load_observer_;
  scoped_ptr<FindInPageNotificationObserver> find_in_page_observer_;

  // True iff we should enable observers that check for initial load conditions.
  bool use_initial_load_observers_;

  // True iff connected to an AutomationProxy.
  bool is_connected_;

  // True iff browser finished loading initial set of tabs.
  bool initial_tab_loads_complete_;

  // True iff the Chrome OS network library finished initialization.
  bool network_library_initialized_;

  // True iff ChromeOS webui login ui is ready.
  bool login_webui_ready_;

  // ID of automation channel.
  std::string channel_id_;

  // Trace data that has been collected but not flushed to the automation
  // client.
  TracingData tracing_data_;

  DISALLOW_COPY_AND_ASSIGN(AutomationProvider);
};

#endif  // CHROME_BROWSER_AUTOMATION_AUTOMATION_PROVIDER_H_


text:
package de.openpizza.android.service;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;

import de.openpizza.android.service.data.OrderRequest;
import de.openpizza.android.service.data.OrderResponse;
import de.openpizza.android.service.restapi.RESTService;
import de.openpizza.android.service.restapi.RESTServiceCall;
import de.openpizza.android.service.restapi.RESTServiceHandler;

public class OrderService extends RESTService<OrderResponse> implements
		RESTServiceCall<OrderRequest, OrderResponse> {
	Gson gson;

	private String id = "0";

	public void setId(String id) {
		this.id = id;
	}

	public OrderService(Activity activity) {
		super(activity);
		gson = new Gson();
	}

	@Override
	public void httpGet(String url, String params,
			RESTServiceHandler<OrderResponse> handler) {
		new GetTask(url, params, handler).execute();
	}

	private class GetTask extends AsyncTask<String, Void, String> {
		private String url;
		private String httpParams;

		public GetTask(String url, String params,
				RESTServiceHandler<OrderResponse> handler) {
			this.url = url;
			this.httpParams = params;
			serviceHandler = handler;
		}

		@Override
		protected void onPreExecute() {
//			dialog.setMessage("Loading...");
//			dialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			return getData(url + "?" + httpParams);
		}

		@Override
		protected void onPostExecute(String result) {
//			dialog.dismiss();
			Log.d("httpget", result);
			serviceHandler.handleGetResponse(gson.fromJson(result,
					OrderResponse.class));
		}
	}

	@Override
	public void httpPost(OrderRequest data,
			RESTServiceHandler<OrderResponse> handler) {
		String json = gson.toJson(data);
		new PostTask(handler).execute(json);
	}

	private class PostTask extends AsyncTask<String, Void, String> {

		public PostTask(RESTServiceHandler<OrderResponse> handler) {
			serviceHandler = handler;
		}

		@Override
		protected void onPreExecute() {
//			dialog.setMessage("Loading...");
//			dialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			return postData("orders/", params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
//			dialog.dismiss();
			Log.d("httppost", result);
			serviceHandler.handlePostResponse(gson.fromJson(result,
					OrderResponse.class));
		}

	}

	@Override
	public void httpPut(OrderRequest data,
			RESTServiceHandler<OrderResponse> handler) {
		String json = gson.toJson(data);
		new PutTask(handler, id).execute(json);
	}

	private class PutTask extends AsyncTask<String, Void, String> {
		private String id;

		public PutTask(RESTServiceHandler<OrderResponse> handler, String id) {
			serviceHandler = handler;
			this.id = id;
		}

		@Override
		protected void onPreExecute() {
//			dialog.setMessage("Loading...");
//			dialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			return postData("orders/" + id, params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
//			dialog.dismiss();
			Log.d("httpput", result);
			serviceHandler.handlePutResponse(gson.fromJson(result,
					OrderResponse.class));
		}

	}
}


text:
[![CircleCI](https://circleci.com/gh/kishaningithub/crudspring.svg?style=shield)](https://circleci.com/gh/kishaningithub/crudspring)
[![Codecov](https://img.shields.io/codecov/c/github/kishaningithub/crudspring.svg)](https://codecov.io/gh/kishaningithub/crudspring)
[![Join the chat at https://gitter.im/crudspring/Lobby](https://badges.gitter.im/crudspring/Lobby.svg)](https://gitter.im/crudspring/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

A CRUD application using spring boot.

# Features
- Your note (A basic crud version of evernote)
    - GET `/api/yournote/v1/notes` Will give you the list of notes
    - POST `/api/yournote/v1/notes` will add a note to the list
    - DELETE `/api/yournote/v1/notes` Will delete all the notes
    - DELETE `/api/yournote/v1/notes/2` Will delete note with id 2
    - PUT `/api/yournote/v1/notes/5` Will replace note with id 5
- Service level
    - `/health` Returns server's health condition (Use of spring actuator)

# Try it out
[![Run in Postman](https://run.pstmn.io/button.svg)](https://app.getpostman.com/run-collection/776b6fa63a1349a47db1)

# Deploy to heroku
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)

# Deploy as docker image
  - docker pull kishanb/crudspring:1.0.0
  - Follow the instructions in [Dockerhub](https://hub.docker.com/r/kishanb/crudspring/)

# System requirements (For development)
- Docker
- Git

# Set up instructions (For development)
- Clone this repo
- ./run
- Point to localhost:5000 and mess with the API
- ./test (Only while running tests)


text:
Planet createPortal(void);

#endif // __PORTAL_H__


text:
import sys
from tempfile import NamedTemporaryFile
from os import remove

try:
    import unittest2 as unittest
    from cStringIO import StringIO
except ImportError:
    from io import StringIO
    import unittest

from edt2ics.cli import write_ical, main, ScheduleScraper

def ctrlC(self, *args, **kwargs):
    raise KeyboardInterrupt

class TestCli(unittest.TestCase):

    def setUp(self):
        self.real_stdout = sys.stdout
        self.stdout = sys.stdout = StringIO()
        self.argv = sys.argv
        self.sys_exit = sys.exit
        self.exit_code = None
        self.ss_init = ScheduleScraper.__init__
        def _fake_exit(code=None):
            self.exit_code = code
        _fake_exit.__name__ = sys.exit.__name__
        sys.exit = _fake_exit

    def tearDown(self):
        sys.stdout = self.real_stdout
        sys.argv = self.argv
        sys.exit = self.sys_exit
        ScheduleScraper.__init__ = self.ss_init

    # write_ical

    def test_write_stdout(self):
        s = u'foobarXz123$$9_=+@@'

        write_ical(s, '-')

        self.stdout.seek(0)
        self.assertEquals(s, self.stdout.read())

    def test_write_file(self):
        s = u'foo&"b$**a-rXz12%x3ZZ$$9_=+@@'
        file_ = NamedTemporaryFile(delete=False)
        file_.close()
        filename = file_.name

        write_ical(s, filename)

        with open(filename, 'r') as f:
            self.assertEquals(s, f.read())

        remove(filename)

    # main

    def test_main_abort_on_interrupt(self):
        ScheduleScraper.__init__ = ctrlC
        sys.argv = ['edt2ics', 'M2']
        self.assertEquals(None, self.exit_code)
        main()
        self.assertEquals(1, self.exit_code)


text:
using System;
using System.IO;
//using System.Collections.Generic;
//using System.Text.RegularExpressions;

namespace tIDE.Format
{
    internal class PathHelper
    {
        public static string GetRelativePath(string basePath, string absolutePath)
        {
            basePath = basePath.Trim();
            if (basePath.Length > 0 && !basePath.EndsWith(Path.DirectorySeparatorChar + ""))
                basePath += Path.DirectorySeparatorChar;

            absolutePath = absolutePath.Trim();

            if (!Path.IsPathRooted(basePath) || !Path.IsPathRooted(absolutePath))
                return absolutePath;

            // absolute path within base
            if (absolutePath.StartsWith(basePath))
                return absolutePath.Remove(0, basePath.Length);

            // remove common root
            while (basePath.Length > 0 && absolutePath.Length > 0)
            {
                if (char.ToLower(basePath[0]) == char.ToLower(absolutePath[0]))
                {
                    basePath = basePath.Remove(0, 1);
                    absolutePath = absolutePath.Remove(0, 1);
                }
                else
                    break;
            }

            int levels = basePath.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Length;
            while (levels-- > 0)
                absolutePath = ".." + Path.DirectorySeparatorChar + absolutePath;

            return absolutePath;
        }

        public static string GetAbsolutePath(string basePath, string relativePath)
        {
            // trim paths from spaces
            basePath = basePath.Trim();
            relativePath = relativePath.Trim();

            // validate path parameters
            if (!Path.IsPathRooted(basePath))
                throw new ArgumentException("Path must be rooted", "basePath");
            if (Path.IsPathRooted(relativePath))
                throw new ArgumentException("Path must be relative", "relativePath");

            // ensure base path has an ending separator
            if (!basePath.EndsWith("" + Path.DirectorySeparatorChar))
                basePath += Path.DirectorySeparatorChar;

            // combine base and relative paths with unprocessed parent directory references
            //string absolutePath = basePath + relativePath;

            //// consume every instance of directory - parent reference pairs e.g. a\b\..\c -> a\c
            //Regex regex = new Regex(@"\\[^\\]+\\\.\.");
            //while (absolutePath.Contains(".."))
            //    absolutePath = regex.Replace(absolutePath, @"");

            string absolutePath = basePath;

            // remove \\ from end of path
            if (absolutePath.EndsWith("\\"))
                absolutePath = Directory.GetParent(absolutePath).ToString();

            // consume every instance of directory - parent reference pairs e.g. a\b\..\c -> a\c
            while (relativePath.Contains("..\\"))
            {
                absolutePath = Directory.GetParent(absolutePath).ToString();
                relativePath = relativePath.Substring(3);
            }

            // ensure base path has an ending separator
            if (!absolutePath.EndsWith("" + Path.DirectorySeparatorChar))
                absolutePath += Path.DirectorySeparatorChar;

            return absolutePath + relativePath;
        }
    }
}


text:
package xcodebuild

import (
	"os"
	"os/exec"

	"github.com/bitrise-io/go-utils/command"
)

/*
xcodebuild [-project <projectname>] \
	-scheme <schemeName> \
	[-destination <destinationspecifier>]... \
	[-configuration <configurationname>] \
	[-arch <architecture>]... \
	[-sdk [<sdkname>|<sdkpath>]] \
	[-showBuildSettings] \
	[<buildsetting>=<value>]... \
	[<buildaction>]...

xcodebuild -workspace <workspacename> \
	-scheme <schemeName> \
	[-destination <destinationspecifier>]... \
	[-configuration <configurationname>] \
	[-arch <architecture>]... \
	[-sdk [<sdkname>|<sdkpath>]] \
	[-showBuildSettings] \
	[<buildsetting>=<value>]... \
	[<buildaction>]...
*/

// TestCommandModel ...
type TestCommandModel struct {
	projectPath string
	isWorkspace bool
	scheme      string
	destination string

	// buildsetting
	generateCodeCoverage bool

	// buildaction
	customBuildActions []string // clean, build

	// Options
	customOptions []string
}

// NewTestCommand ...
func NewTestCommand(projectPath string, isWorkspace bool) *TestCommandModel {
	return &TestCommandModel{
		projectPath: projectPath,
		isWorkspace: isWorkspace,
	}
}

// SetScheme ...
func (c *TestCommandModel) SetScheme(scheme string) *TestCommandModel {
	c.scheme = scheme
	return c
}

// SetDestination ...
func (c *TestCommandModel) SetDestination(destination string) *TestCommandModel {
	c.destination = destination
	return c
}

// SetGenerateCodeCoverage ...
func (c *TestCommandModel) SetGenerateCodeCoverage(generateCodeCoverage bool) *TestCommandModel {
	c.generateCodeCoverage = generateCodeCoverage
	return c
}

// SetCustomBuildAction ...
func (c *TestCommandModel) SetCustomBuildAction(buildAction ...string) *TestCommandModel {
	c.customBuildActions = buildAction
	return c
}

// SetCustomOptions ...
func (c *TestCommandModel) SetCustomOptions(customOptions []string) *TestCommandModel {
	c.customOptions = customOptions
	return c
}

func (c *TestCommandModel) cmdSlice() []string {
	slice := []string{toolName}

	if c.projectPath != "" {
		if c.isWorkspace {
			slice = append(slice, "-workspace", c.projectPath)
		} else {
			slice = append(slice, "-project", c.projectPath)
		}
	}

	if c.scheme != "" {
		slice = append(slice, "-scheme", c.scheme)
	}

	if c.generateCodeCoverage {
		slice = append(slice, "GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES", "GCC_GENERATE_TEST_COVERAGE_FILES=YES")
	}

	slice = append(slice, c.customBuildActions...)
	slice = append(slice, "test")
	if c.destination != "" {
		slice = append(slice, "-destination", c.destination)
	}
	slice = append(slice, c.customOptions...)

	return slice
}

// PrintableCmd ...
func (c TestCommandModel) PrintableCmd() string {
	cmdSlice := c.cmdSlice()
	return command.PrintableCommandArgs(false, cmdSlice)
}

// Command ...
func (c TestCommandModel) Command() *command.Model {
	cmdSlice := c.cmdSlice()
	return command.New(cmdSlice[0], cmdSlice[1:]...)
}

// Cmd ...
func (c TestCommandModel) Cmd() *exec.Cmd {
	command := c.Command()
	return command.GetCmd()
}

// Run ...
func (c TestCommandModel) Run() error {
	command := c.Command()

	command.SetStdout(os.Stdout)
	command.SetStderr(os.Stderr)

	return command.Run()
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Exercise 2: ParserDocHandler Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Exercise 2

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Public Member Functions |
Private Member Functions |
Private Attributes |
List of all members

ParserDocHandler Class Reference

Parses the XML document.
 More...

Inheritance diagram for ParserDocHandler:

  <map id="ParserDocHandler_map" name="ParserDocHandler_map">
</map>

Public Member Functions

 	ParserDocHandler ()

 	Creates an instance of the ParserDocHandler class.  More...

void 	startElement (const XMLCh *const name, AttributeList &atts)

 	Method that writes day, hour and value from parsed data to file.  More...

 	~ParserDocHandler ()

 	Deconstructor of the ParserDocHandler class.  More...

Private Member Functions

string 	doubleHH (string HH)

 	A method to make the "hour" value double digits.  More...

Private Attributes

int 	trigger = 0

 	if trigger == 1, there are changes worth writing to csv.txt. Else do nothing.  More...

string 	dd

 	variable to store date.  More...

string 	hh

 	variable to store hour.  More...

string 	vv

 	variable to store values.  More...

string 	csvFileName = "csv.txt"

 	filename of csv file.  More...

XMLCh * 	gasDay = XMLString::transcode("gasDay")

 	XMLCh* type variable of string "gasDay" for parser.  More...

XMLCh * 	date = XMLString::transcode("date")

 	XMLCh* type variable of string "date" for parser.  More...

XMLCh * 	time = XMLString::transcode("time")

 	XMLCh* type variable of string "time" for parser.  More...

XMLCh * 	hour = XMLString::transcode("hour")

 	XMLCh* type variable of string "hour" for parser.  More...

XMLCh * 	amtP = XMLString::transcode("amountOfPower")

 	XMLCh* type variable of string "amountOfPower" for parser.  More...

XMLCh * 	value = XMLString::transcode("value")

 	XMLCh* type variable of string "value" for parser.  More...

ofstream 	csv

Detailed Description

Parses the XML document.

The ParserDocHandler class inheirts the HandlerBase class of Xerus, which does nothing to a parsed document. Class reads XML document and get date under gasDay,

Constructor & Destructor Documentation

          ParserDocHandler::ParserDocHandler
          (
          	)

inline

Creates an instance of the ParserDocHandler class.

          ParserDocHandler::~ParserDocHandler
          (
          	)

inline

Deconstructor of the ParserDocHandler class.

Member Function Documentation

          string ParserDocHandler::doubleHH
          (
          string
          HH	)

inlineprivate

A method to make the "hour" value double digits.

Parameters

HH	cast as string

Returns

Returns 01, 02, ... , 24.

          void ParserDocHandler::startElement
          (
          const XMLCh *const
          name,

          AttributeList &
          atts

          )

inline

Method that writes day, hour and value from parsed data to file.

Parameters

name	the element name to be compared.

atts	the list of attributes.

Returns

None.

Member Data Documentation

          XMLCh* ParserDocHandler::amtP = XMLString::transcode("amountOfPower")

private

XMLCh* type variable of string "amountOfPower" for parser.

          ofstream ParserDocHandler::csv

private

          string ParserDocHandler::csvFileName = "csv.txt"

private

filename of csv file.

          XMLCh* ParserDocHandler::date = XMLString::transcode("date")

private

XMLCh* type variable of string "date" for parser.

          string ParserDocHandler::dd

private

variable to store date.

          XMLCh* ParserDocHandler::gasDay = XMLString::transcode("gasDay")

private

XMLCh* type variable of string "gasDay" for parser.

          string ParserDocHandler::hh

private

variable to store hour.

          XMLCh* ParserDocHandler::hour = XMLString::transcode("hour")

private

XMLCh* type variable of string "hour" for parser.

          XMLCh* ParserDocHandler::time = XMLString::transcode("time")

private

XMLCh* type variable of string "time" for parser.

          int ParserDocHandler::trigger = 0

private

if trigger == 1, there are changes worth writing to csv.txt. Else do nothing.

          XMLCh* ParserDocHandler::value = XMLString::transcode("value")

private

XMLCh* type variable of string "value" for parser.

          string ParserDocHandler::vv

private

variable to store values.

The documentation for this class was generated from the following file:

ex2.cxx

<address class="footer">
Generated on Mon Jun 5 2017 12:21:25 for Exercise 2 by

 1.8.9.1
</address>


text:
sledge-js
=========

A collection of JavaScipt functions to load Goldsource and Source map files and render them. Not an editor.


text:
module Intersail
  module ZfClient
    class ZProcessProperty
      include ActiveModel::Model

      attr_accessor :name
      attr_accessor :value

      validates_presence_of :name
      validates_presence_of :value

    end
  end
end


text:
<?php

namespace Kunstmaan\AdminListBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\AdminBundle\Entity\AbstractEntity;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="Kunstmaan\AdminListBundle\Repository\LockableEntityRepository")
 * @ORM\Table(name="kuma_lockable_entity",
 *    uniqueConstraints={@ORM\UniqueConstraint(name="ix_kuma_lockable_entity_id_class", columns={"entity_id", "entity_class"})},
 *    indexes={@ORM\Index(name="idx__lockable_entity_id_class", columns={"entity_id", "entity_class"})}
 * )
 */
class LockableEntity extends AbstractEntity
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     */
    protected $updated;

    /**
     * @var string
     *
     * @ORM\Column(type="string", name="entity_class")
     */
    protected $entityClass;

    /**
     * @var integer
     *
     * @ORM\Column(type="bigint", name="entity_id")
     */
    protected $entityId;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->setCreated(new \DateTime());
        $this->setUpdated(new \DateTime());
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     *
     * @return LockableEntity
     */
    public function setCreated(\DateTime $created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     *
     * @return LockableEntity
     */
    public function setUpdated(\DateTime $updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Get entityClass.
     *
     * @return string.
     */
    public function getEntityClass()
    {
        return $this->entityClass;
    }

    /**
     * @param $entityClass
     *
     * @return LockableEntity
     */
    public function setEntityClass($entityClass)
    {
        $this->entityClass = $entityClass;

        return $this;
    }

    /**
     * Get entityId.
     *
     * @return integer.
     */
    public function getEntityId()
    {
        return $this->entityId;
    }

    /**
     * Set integer
     *
     * @param $entityId
     *
     * @return LockableEntity
     */
    public function setEntityId($entityId)
    {
        $this->entityId = $entityId;

        return $this;
    }
}


text:
.. highlight:: javascript

Plugin Recipes
==============

Below is a collection of useful plugin "recipes" that you might find helpful.

data-language
-------------

Let's say you'd like to track the language that was auto-detected via a
`data attribute <https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes>`_.
This might prove useful if you desired to add a dynamic label
via CSS with ``:before``, etc.

::

    hljs.addPlugin( {
      'after:highlightElement': ({el, result}) => {
        // move the language from the result into the dataset
        el.dataset.language = result.language }
    })


text:
$(function(){
  var encdigest = $('#encdigest').val();
  if (encdigest) {
    var name = $('#name').val();
    var digest = $('#digest').val();
    localStorage.setItem(encdigest + ':name', name);
    localStorage.setItem(encdigest + ':digest', digest);
  }
  $('#apply').click(function () {
    var textdata = $('#textdata');
    if (textdata) {
      //var metadata = textdata.contents()[0].body.innerHTML;
      var metadata = $('pre', textdata.contents()).text(); // TODO Chrome only?
      $(metadata.split('\n')).each(function (i, x) {
        var kv = x.split('=');
        var k = kv[0];
        var v = kv[1];
        if (!!v) {
          if (v.length == 0) {
            localStorage.removeItem(k);
          }
          else {
            localStorage.setItem(k, v);
          }
        }
        else if (k) {
          localStorage.removeItem(k);
        }
      });
    }
  });
});


text:
{% extends "common/base.html" %}

{% block title %}
  <title>OOI Science</title>
{% endblock %}

{% block head %}
  <link href="/css/compiled/index.css" rel="stylesheet" type="text/css" />

{% endblock %}

{% block body %}

               Map Section

                Plot Controls

                 Plot Section

{% endblock %}